Debian Codegraph @

CorsixTH/Lua/app.lua

raw
1 --[[ Copyright (c) 2009 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local pathsep = package.config:sub(1, 1)
22 local rnc = require("rnc")
23 local lfs = require("lfs")
24 local TH = require("TH")
25 local SDL = require("sdl")
26
27 -- Increment each time a savegame break would occur
28 -- and add compatibility code in afterLoad functions
29 -- Recommended: Also replace/Update the summary comment
30
31 local SAVEGAME_VERSION = 253 -- 0.70.0
32
33 class "App"
34
35 ---@type App
36 local App = _G["App"]
37
38 App.MIN_WINDOW_WIDTH = 640
39 App.MIN_WINDOW_HEIGHT = 480
40
41 function App:App()
42 self.command_line = {}
43 self.config = {}
44 self.hotkeys = {}
45 self.runtime_config = {}
46 self.key_modifiers = {}
47 self.gfx = {}
48 self.eventHandlers = {
49 frame = self.drawFrame,
50 timer = self.onTick,
51 keydown = self.onKeyDown,
52 keyup = self.onKeyUp,
53 textediting = self.onEditingText,
54 textinput = self.onTextInput,
55 buttonup = self.onMouseUp,
56 buttondown = self.onMouseDown,
57 mousewheel = self.onMouseWheel,
58 motion = self.onMouseMove,
59 active = self.onWindowActive,
60 window_resize = self.onWindowResize,
61 music_over = self.onMusicOver,
62 movie_over = self.onMovieOver,
63 sound_over = self.onSoundOver,
64 multigesture = self.onMultiGesture
65 }
66 self.strings = {}
67 self.savegame_version = SAVEGAME_VERSION
68 self.check_for_updates = TH.GetCompileOptions().update_check
69 self.idle_tick = 0
70 self.window_active_status = false -- whether window is in focus, set after App:init
71 end
72
73 function App:setCommandLine(...)
74 self.command_line = { ... }
75 for _, arg in ipairs(self.command_line) do
76 local setting, value = arg:match("^%-%-([^=]*)=(.*)$") --setting=value
77 if value then
78 self.command_line[setting] = value
79 end
80 end
81 end
82
83 --! Returns the full path of the local path given
84 --!param folders (string or table) A string of one segment or an set of many segments of the path
85 --!param trailing_slash (boolean) Whether the path needs to end with a local path separator
86 --!return fullpath (string) The OS dependent full path
87 function App:getFullPath(folders, trailing_slash)
88 if type(folders) ~= "table" then folders = {folders} end
89 local ending = trailing_slash and pathsep or ""
90 return debug.getinfo(1, "S").source:sub(2, -12) .. table.concat(folders, pathsep) .. ending
91 end
92
93 function App:init()
94 -- App initialisation 1st goal: Get the loading screen up
95
96 print("")
97 print("")
98 print("---------------------------------------------------------------")
99 print("")
100 print("Welcome to CorsixTH " .. self:getReleaseString() .. "!")
101 print("")
102 print("---------------------------------------------------------------")
103 print("")
104 print("This window will display useful information if an error occurs.")
105 print("")
106 print("---------------------------------------------------------------")
107 print("")
108
109 -- Prereq 1: C++ and lua sides are compatible
110 local compile_opts = TH.GetCompileOptions()
111 local api_version = corsixth.require("api_version")
112 if api_version ~= compile_opts.api_version then
113 api_version = api_version or 0
114 compile_opts.api_version = compile_opts.api_version or 0
115 if api_version < compile_opts.api_version then
116 print("Notice: Compiled binary is more recent than Lua scripts.")
117 elseif api_version > compile_opts.api_version then
118 print("Warning: Compiled binary is out of date. CorsixTH will likely" ..
119 " fail to run until you recompile the binary.")
120 end
121 end
122
123 -- Prereq 2: Config file (for screen width / height / TH folder)
124 -- Note: These errors cannot be translated, as the config file specifies the language
125 local conf_path = self.command_line["config-file"] or "config.txt"
126 local _, conf_err = require('config_finder').load_config(conf_path, self.config)
127 if conf_err then
128 error("Unable to load the config file. Please ensure that CorsixTH " ..
129 "has permission to read/write " .. conf_path .. ", or use the " ..
130 "--config-file=filename command line option to specify a writable file. " ..
131 "For reference, the error loading the config file was: " .. conf_err)
132 end
133 self:fixConfig()
134 corsixth.require("filesystem")
135 local good_install_folder, error_message, charset = self:checkInstallFolder()
136 self.good_install_folder = good_install_folder
137 self.level_dir = self:getFullPath("Levels", true)
138 self.campaign_dir = self:getFullPath("Campaigns", true)
139 self:initUserDirectories()
140 self:initSavegameDir()
141 self:initScreenshotsDir()
142
143 -- Create the window
144 if not SDL.init("video", "timer", "audio") then
145 return false, "Cannot initialise SDL"
146 end
147
148 -- Report operating system (possible values: "windows", "macos", "unix")
149 self.os = compile_opts.os
150
151 local modes = {}
152 self.fullscreen = false
153 if self.config.fullscreen then
154 self.fullscreen = true
155 modes[#modes + 1] = "fullscreen"
156 end
157 if self.config.track_fps then
158 modes[#modes + 1] = "present immediate"
159 end
160 if self.config.direct_zoom == nil or self.config.direct_zoom then
161 modes[#modes + 1] = "direct zoom"
162 end
163 self.modes = modes
164 self.video = assert(TH.surface(
165 self.config.width,
166 self.config.height,
167 App.MIN_WINDOW_WIDTH * self.config.ui_scale,
168 App.MIN_WINDOW_HEIGHT * self.config.ui_scale,
169 unpack(modes)))
170 self.video:setBlueFilterActive(false)
171 SDL.wm.setIconWin32()
172
173 self.caption = "CorsixTH"
174 if self.config.track_fps then
175 SDL.trackFPS(true)
176 SDL.limitFPS(false)
177 end
178
179
180 -- Create gamelog file.
181 self:initGamelogFile()
182
183 -- Prereq 2: Load and initialise the graphics subsystem
184 corsixth.require("persistance")
185 corsixth.require("graphics")
186 local gfx_set = good_install_folder and (self.using_demo_files and "demo" or "full") or "base"
187 self.gfx = Graphics(self, gfx_set, charset)
188
189 -- Put up the loading screen
190 if good_install_folder then
191 self.video:startFrame()
192 self.gfx:loadRaw("Load01V", 640, 480):draw(self.video,
193 math.floor((self.config.width - 640) / 2), math.floor((self.config.height - 480) / 2))
194 self.video:endFrame()
195 -- Add some notices to the loading screen
196 local notices = {}
197 local font = self.gfx:loadBuiltinFont()
198 if self.gfx:hasLanguageFont("unicode") then
199 notices[#notices + 1] = TH.freetype_font.getCopyrightNotice()
200 font = self.gfx:loadLanguageFont("unicode", font:getSheet())
201 end
202 notices = table.concat(notices)
203 if notices ~= "" then
204 self.video:startFrame()
205 self.gfx:loadRaw("Load01V", 640, 480):draw(self.video,
206 math.floor((self.config.width - 640) / 2), math.floor((self.config.height - 480) / 2))
207 font:drawWrapped(self.video, notices, 32,
208 math.floor((self.config.height + 400) / 2), math.floor(self.config.width - 64), "center")
209 self.video:endFrame()
210 end
211 end
212
213 -- App initialisation 2nd goal: Load remaining systems and data in an appropriate order
214
215 math.randomseed(os.time() + SDL.getTicks())
216 -- The following psuedo-random number generators are based on different
217 -- disritubtion algorithms. For explanations and how to use them see the Wiki
218
219 -- Add math.t_random globally.
220 -- It generates pseudo random triangular distributed numbers in interval (a, b)
221 -- mostly around c between a and b.
222 strict_declare_global "math.t_random"
223 math.t_random = function(a, c, b)
224 assert(a < c, "Left boundary a should be less than center c.")
225 assert(c < b, "Right boundary b should more than center c.")
226 -- normalize c (a -> 0, b -> 1)
227 local range = b - a
228 c = (c - a) / range
229
230 local u = math.random()
231 if u <= c then
232 return a + math.sqrt(c * u) * range
233 else
234 return a + (1 - math.sqrt((1 - c) * (1 - u))) * range
235 end
236 end
237
238 -- Add math.n_random globally. It generates pseudo random normally distributed
239 -- numbers using the Box-Muller transform.
240 strict_declare_global "math.n_random"
241 math.n_random = function(mean, variance)
242 return mean + math.sqrt(-2 * math.log(math.random()))
243 * math.cos(2 * math.pi * math.random()) * variance
244 end
245
246 -- Add math.p_random globally.
247 -- It generates pseudo random Poisson distributed numbers.
248 -- Algorithm by Junhao for large mean value support, based on Knuths algorithm.
249 -- See also: https://en.wikipedia.org/wiki/Poisson_distribution
250 strict_declare_global "math.p_random"
251 math.p_random = function(mean)
252 local STEP = 500
253 local mean_left = mean
254 local k = 0
255 local p = 1
256 while true do
257 k = k + 1
258 -- Draw a non-zero random value.
259 local u = 0
260 while u == 0 do u = math.random() end
261 p = p * u
262
263 while p < 1 and mean_left > 0 do
264 if mean_left > STEP then
265 p = p * math.exp(STEP)
266 mean_left = mean_left - STEP
267 else
268 p = p * math.exp(mean_left)
269 mean_left = 0
270 end
271 end
272
273 if p <= 1 then break end
274 end
275 return k - 1
276 end
277
278 -- Also add the nice-to-have function math.round
279 strict_declare_global "math.round"
280 math.round = function(input)
281 return math.floor(input + 0.5)
282 end
283 -- Load audio
284 corsixth.require("audio")
285 self.audio = Audio(self)
286 self:initMusicDir()
287 self.audio:init()
288
289 -- Hack to early initialise the audio and reduce delay on Windows
290 self.audio:playRandomBackgroundTrack()
291 self.audio:stopBackgroundTrack()
292
293 -- Load movie player
294 corsixth.require("movie_player")
295 self.moviePlayer = MoviePlayer(self, self.audio, self.video)
296 if good_install_folder then
297 self.moviePlayer:init()
298 end
299
300 -- Load strings before UI and before additional Lua
301 corsixth.require("strings")
302 corsixth.require("string_extensions")
303 self.strings = Strings(self)
304 self.strings:init()
305 local language_load_success, language_error = self:initLanguage()
306 if (self.command_line.dump or ""):match("strings") then
307 -- Specify --dump=strings on the command line to dump strings
308 -- (or insert "true or" after the "if" in the above)
309 self:dumpStrings()
310 end
311
312 -- Load/setup hotkeys.
313 local hotkeys_path = self.command_line["hotkeys-file"] or "hotkeys.txt"
314 local _, hotkeys_err = require('config_finder').load_hotkeys(hotkeys_path, self.hotkeys)
315 if hotkeys_err then
316 error(_S.hotkeys_file_err.file_err_01 .. hotkeys_path .. _S.hotkeys_file_err.file_err_02 .. hotkeys_err)
317 end
318 self:fixHotkeys()
319
320 -- Load map before world
321 corsixth.require("map")
322
323 -- Load additional Lua before world
324 if good_install_folder then
325 self.anims = self.gfx:loadAnimations("Data", "V")
326 self.animation_manager = AnimationManager(self.anims)
327 self.walls = self:loadLuaFolder("walls")
328 corsixth.require("entity")
329 corsixth.require("entities.humanoid")
330 corsixth.require("entities.object")
331 corsixth.require("entities.machine")
332
333 local objects = self:loadLuaFolder("objects")
334 self.objects = self:loadLuaFolder("objects/machines", nil, objects)
335 -- Doors are in their own folder to ensure that the swing doors (which
336 -- depend on the door) are loaded after the door object.
337 self.objects = self:loadLuaFolder("objects/doors", nil, objects)
338 for _, v in ipairs(self.objects) do
339 if v.slave_id then
340 v.slave_type = self.objects[v.slave_id]
341 v.slave_type.master_type = v
342 end
343 Object.processTypeDefinition(v)
344 end
345
346 corsixth.require("room")
347 self.rooms = self:loadLuaFolder("rooms")
348
349 corsixth.require("humanoid_action")
350 self.humanoid_actions = self:loadLuaFolder("humanoid_actions")
351
352 local diseases = self:loadLuaFolder("diseases")
353 self.diseases = self:loadLuaFolder("diagnosis", nil, diseases)
354
355 -- Load world before UI
356 corsixth.require("world")
357 end
358
359 -- Load UI
360 corsixth.require("ui")
361 if good_install_folder then
362 corsixth.require("game_ui")
363 self.ui = UI(self, true)
364 else
365 self.ui = UI(self, true)
366 self.ui:setMenuBackground()
367 local function callback(path)
368 TheApp.config.theme_hospital_install = path
369 TheApp:saveConfig()
370 TheApp:reset()
371 end
372
373 self.ui:addWindow(UIDirectoryBrowser(self.ui, nil, _S.install.th_directory, "InstallDirTreeNode", callback))
374 return true
375 end
376
377
378 -- Load main menu (which creates UI)
379 local function callback_after_movie()
380 self:loadMainMenu()
381 self.audio:playRandomBackgroundTrack()
382
383 -- If we couldn't properly load the language, show an information dialog
384 if not language_load_success then
385 -- At this point we know the language is english, so no use having
386 -- localized strings.
387 self.ui:addWindow(UIInformation(self.ui, { language_error }))
388 end
389
390 -- If the player wants to continue then load the youngest file in the Autosaves folder
391 -- If they give a month number then load that month's autosave
392 if self.command_line.continue then
393 local num = self.command_line.continue
394 local file = "Autosaves" .. pathsep .. "Autosave" .. num .. ".sav"
395 if num >= "1" and num <= "12" and lfs.attributes(self.savegame_dir .. file, "size") then
396 self.command_line.load = file
397 else
398 self.command_line.load = "Autosaves" .. pathsep ..
399 FileTreeNode(self.savegame_dir .. "Autosaves"):getMostRecentlyModifiedChildFile(".%.sav$").label
400 end
401 end
402 -- If a savegame was specified, load it
403 if self.command_line.load then
404 local status, err = pcall(self.load, self, self.savegame_dir .. self.command_line.load)
405 if not status then
406 err = _S.errors.load_prefix .. err
407 print(err)
408 self.ui:addWindow(UIInformation(self.ui, { err }))
409 end
410 end
411 -- There might also be a message from the earlier initialization process that should be shown.
412 -- Show it using the built-in font in case the game's font is messed up.
413 if error_message then
414 self.ui:addWindow(UIInformation(self.ui, error_message, true))
415 end
416 end
417
418 -- Finished init, save any config changes applied
419 TheApp:saveConfig()
420 TheApp:saveHotkeys()
421
422 if self.config.play_intro then
423 self.moviePlayer:playIntro(callback_after_movie)
424 else
425 callback_after_movie()
426 end
427 return true
428 end
429
430 --! Create the gamelog, using the launch time in the filename, and write the system information.
431 function App:initGamelogFile()
432 self.gamelog_path = self.user_log_dir .. os.date("%y-%m-%d--%H-%M-%S--gamelog.txt", os.time(os.date("*t")))
433 local fi, success = self:writeToFileOrTmp(self.gamelog_path)
434 local sysinfo = self:gamelogHeader()
435 fi:write(sysinfo)
436 fi:close()
437 if success then self:trimLogs() end -- Only trim logs if logs folder is writable
438 end
439
440 --! Trims the logs folder of old game logs down to ten files.
441 function App:trimLogs()
442 local log_retention, log_table = 11, {}
443 for node in lfs.dir(self.user_log_dir) do
444 local file = self.user_log_dir .. pathsep .. node
445 if node:sub(-12) == "-gamelog.txt" then
446 table.insert(log_table, file)
447 end
448 end
449 table.sort(log_table,
450 function(a, b) return lfs.attributes(a, "modification") > lfs.attributes(b, "modification") end)
451 for i=log_retention, #log_table do os.remove(log_table[i]) end
452 end
453
454 function App:getConfigPath()
455 return self.command_line["config-file"] or "config.txt"
456 end
457
458 function App:getDefaultScreenshotsDir()
459 local conf_path = self:getConfigPath()
460 return conf_path:match("^(.-)[^" .. pathsep .. "]*$") .. "Screenshots"
461 end
462
463 function App:getDefaultSavegameDir()
464 local conf_path = self:getConfigPath()
465 return conf_path:match("^(.-)[^" .. pathsep .. "]*$") .. "Saves"
466 end
467
468 --! Tries to initialize the user level and campaign directories
469 -- TODO: Integrate other directory initialisations into this function
470 function App:initUserDirectories()
471 local conf_path = self:getConfigPath()
472
473 -- Attempt to set the user's directory choice
474 -- param dir (path) The defined path of the folder by the user
475 -- param label (string) What folder was being set if there was an error
476 -- return The fully qualified path
477 local function setUserDir(dir, label)
478 dir = dir:sub(-1, -1) == pathsep and dir:sub(1, -2) or dir
479 if lfs.attributes(dir, "mode") ~= "directory" and not lfs.mkdir(dir) then
480 -- A failed directory creation does not result in a crash. But the user may lose
481 -- the ability to load/save properly.
482 print("Warning: " .. label .. " directory does not exist and could not be created.")
483 end
484 dir = dir:sub(-1, -1) ~= pathsep and dir .. pathsep or dir
485 return dir
486 end
487
488 self.user_level_dir = self.config.levels or
489 conf_path:match("^(.-)[^" .. pathsep .. "]*$") .. "Levels"
490 self.user_level_dir = setUserDir(self.user_level_dir, "User Levels")
491 self.user_campaign_dir = self.config.campaigns or
492 conf_path:match("^(.-)[^" .. pathsep .. "]*$") .. "Campaigns"
493 self.user_campaign_dir = setUserDir(self.user_campaign_dir, "User Campaigns")
494 self.user_log_dir = self.config.logs or
495 conf_path:match("^(.-)[^" .. pathsep .. "]*$") .. "Logs"
496 self.user_log_dir = setUserDir(self.user_log_dir, "Gamelogs")
497 end
498
499 --! Tries to initialize the savegame directory, returns true on success and
500 --! false on failure.
501 function App:initSavegameDir()
502 local default_savegame_dir = self:getDefaultSavegameDir()
503 self.savegame_dir = self.config.savegames or default_savegame_dir
504
505 if self.savegame_dir:sub(-1, -1) == pathsep then
506 self.savegame_dir = self.savegame_dir:sub(1, -2)
507 end
508 if lfs.attributes(self.savegame_dir, "mode") ~= "directory" then
509 if not lfs.mkdir(self.savegame_dir) then
510 print("Notice: Savegame directory does not exist and could not be created.")
511 return false
512 end
513 end
514 if self.savegame_dir:sub(-1, -1) ~= pathsep then
515 self.savegame_dir = self.savegame_dir .. pathsep
516 end
517 return true
518 end
519
520 function App:initScreenshotsDir()
521 local default_screenshots_dir = self:getDefaultScreenshotsDir()
522 self.screenshot_dir = self.config.screenshots or default_screenshots_dir
523
524 if self.screenshot_dir:sub(-1, -1) == pathsep then
525 self.screenshot_dir = self.screenshot_dir:sub(1, -2)
526 end
527 if lfs.attributes(self.screenshot_dir, "mode") ~= "directory" then
528 if not lfs.mkdir(self.screenshot_dir) then
529 print("Notice: Screenshot directory does not exist and could not be created.")
530 return false
531 end
532 end
533 if self.screenshot_dir:sub(-1, -1) ~= pathsep then
534 self.screenshot_dir = self.screenshot_dir .. pathsep
535 end
536 return true
537 end
538
539 function App:initMusicDir()
540 -- No need to set the music dir if it's already configured
541 if self.config.audio_music then
542 if isDirectory(self.config.audio_music) then
543 return
544 else
545 print("Warning: Configured music directory '" .. self.config.audio_music .. "' is not a valid directory.")
546 self.config.audio_music = nil
547 end
548 end
549
550 -- Checks if the given directory name is a valid music directory name
551 local function isValidMusicDirName(name)
552 local posible_dirs = {"music"}
553
554 for _, valid_name in ipairs(posible_dirs) do
555 if name == valid_name then
556 return true
557 end
558 end
559 return false
560 end
561
562 -- Checks if the specified directory has music files
563 local function dirHasMusic(path)
564 -- Build a lookup table of allowed extensions (waveform + instructional)
565 local waveform = list_to_set(self.audio.allowed_waveform_formats)
566 local instructional = list_to_set(self.audio.allowed_instructional_formats)
567
568 -- Scan directory for files with matching extensions
569 for file in lfs.dir(path) do
570 local ext = file:match("%.([^.]+)$")
571 if ext and (waveform[ext:upper()] or instructional[ext:upper()]) then
572 return true
573 end
574 end
575
576 return false
577 end
578
579 -- Checks if the specified path contains a music directory and if it has music files
580 -- If found, the directory's path is returned
581 local function findMusicDir(path)
582 if path == nil or not isDirectory(path) then
583 return nil
584 end
585
586 local normalized_path = stripTrailingSlashes(path)
587
588 -- Check every file and folder inside the given path
589 for entry in lfs.dir(normalized_path) do
590 local entry_path = normalized_path .. "/" .. entry -- paths with "/" work on all operating systems
591
592 if isValidMusicDirName(entry:lower()) and
593 canOpenDirectory(entry_path) and
594 dirHasMusic(entry_path)
595 then
596 return entry_path
597 end
598 end
599 return nil
600 end
601
602 local operating_system = self.os
603 local corsixth_path = lfs.currentdir()
604 local conf_path = self.command_line["config-file"] or nil -- Gets the path of the config file ('nil' if it's in CorsixTH's dir)
605 conf_path = conf_path:match("^(.-)[^" .. pathsep .. "]*$") -- Removes the config file name from the above path
606
607 if(operating_system == "macos") then
608 -- On macOS skip checking the game's directory, since it's difficult to obtain and/or open
609 corsixth_path = nil
610 end
611
612 -- Check corsixth's install directory first, then the config file directory
613 local music_dir = findMusicDir(conf_path) or findMusicDir(corsixth_path)
614 if music_dir then
615 self.config.audio_music = music_dir
616 end
617
618 -- self:saveConfig() --> Don't save the config here, it'll get saved later in the app initialization process
619 end
620
621 --! Initialises the application's language based on the player's choice.
622 --!return success (boolean) Whether the chosen language was initialised
623 --!return err (string) What to report back to the player on failure
624 function App:initLanguage()
625 -- Make sure that we can actually show the desired language.
626 -- If we can't, work out the most common issue and reset to a revert to a
627 -- language that is likely to be supported for the version of Theme Hospital
628 -- the player has.
629 local success, err = true, nil
630 local language = self.config.language
631
632 -- Revert to Russian for the Russian regional release of Theme Hospital or
633 -- English otherwise.
634 --
635 -- When we support more regional versions of Theme Hospital this function
636 -- should be extended to cover those as well.
637 local function revertToSupportedLanguage()
638 local l
639 if self.gfx:hasLanguageFont("cp437") then
640 l = [[English]]
641 elseif self.gfx:hasLanguageFont("mik") then
642 l = [[Russian]]
643 else
644 print("Warning: No suitable font found. Defaulting to English, but the game may be broken.")
645 l = [[English]]
646 end
647 self.config.language = l
648 self:saveConfig()
649 success = false
650 end
651
652 local exists = self.strings:checkLanguageExists(language)
653 if not exists then
654 revertToSupportedLanguage()
655 err = "The game language set in the configuration file '" .. language ..
656 "' was not valid. It has been reverted to '" .. self.config.language ..
657 "'. Please select your desired language from the Settings screen again."
658 language = self.config.language
659 end
660
661 local font = self.strings:getFont(language)
662 if self.gfx:hasLanguageFont(font) then
663 self.gfx.language_font = font
664 else
665 revertToSupportedLanguage()
666 err = "The game language has been reverted to '" .. self.config.language ..
667 "' because the desired language '" .. language .. "' could not be loaded." ..
668 " Please make sure you have specified a font file in Settings-Folders-Font or the" ..
669 " configuration file."
670 self.gfx.language_font = self.strings:getFont(self.config.language)
671 language = self.config.language
672 end
673
674 local strings, speech_file = self.strings:load(language)
675 strict_declare_global "_S"
676 strict_declare_global "_A"
677 local old_S = _S
678 _S = strings
679 -- For immediate compatibility:
680 getmetatable(_S).__call = function(_, sec, str, ...)
681 assert(_S.deprecated[sec] and _S.deprecated[sec][str],
682 "_S(" .. sec .. ", " .. str .. ") does not exist!")
683
684 str = _S.deprecated[sec][str]
685 if ... then
686 str = str:format(...)
687 end
688 return str
689 end
690 if old_S then
691 unpermanent "_S"
692 end
693 _S = permanent("_S", TH.stringProxy(_S))
694 if old_S then
695 TH.stringProxy.reload(old_S, _S)
696 end
697 _A = self.strings:setupAdviserMessage(_S.adviser)
698
699 self.gfx:onChangeLanguage()
700 if self.ui then
701 self.ui:onChangeLanguage()
702 end
703 self.audio:initSpeech(speech_file)
704 return success, err
705 end
706
707 function App:worldExited()
708 self.audio:clearCallbacks()
709 end
710
711 --! Initialise CorsixTH's main menu screen including relevant windows
712 --!param message (string) Something to display to the user
713 function App:loadMainMenu(message)
714 if self.world then
715 self:worldExited()
716 end
717
718 -- Make sure there is no blue filter active.
719 self.video:setBlueFilterActive(false)
720
721 -- Unload ui, world and map
722 self.ui = nil
723 self.world = nil
724 self.map = nil
725
726 self.ui = UI(self)
727 self.ui:setMenuBackground()
728 self.ui:addWindow(UIMainMenu(self.ui))
729 self.ui:addWindow(UITipOfTheDay(self.ui))
730
731 -- Show update window if there's an update
732 self:checkForUpdates()
733
734 -- If a message was supplied, show it
735 if message then
736 self.ui:addWindow(UIInformation(self.ui, message))
737 end
738
739 -- Reset the idle tick counter
740 self:resetIdle()
741 end
742
743 --! Sets the mouse capture to the state set within
744 --! app.config.capture_mouse
745 function App:setCaptureMouse()
746 self.video:setCaptureMouse(self.config.capture_mouse)
747 end
748
749 --! Loads the first level of the specified campaign and prepares the world
750 --! to be able to progress through that campaign.
751 --!param campaign_file (string) Full path of a CorsixTH Campaign definition Lua file.
752 function App:loadCampaign(campaign_file)
753 local campaign_info, level_info, errors, _
754
755 campaign_info, errors = self:readCampaignFile(campaign_file)
756 if not campaign_info then
757 self.ui:addWindow(UIInformation(self.ui, { _S.errors.could_not_load_campaign:format(errors) }))
758 return
759 end
760 campaign_info.folder = campaign_file:match("(.*" .. pathsep .. ")")
761
762 level_info, errors = self:readLevelFile(campaign_info.levels[1], campaign_info.folder)
763 if not level_info then
764 self.ui:addWindow(UIInformation(self.ui, { _S.errors.could_not_find_first_campaign_level:format(errors) }))
765 return
766 end
767
768 _, errors = self:readMapDataFile(level_info.map_file)
769 if errors then
770 self.ui:addWindow(UIInformation(self.ui, { errors }))
771 return
772 end
773
774 -- Use localised description and winning text, if available
775 campaign_info.description = self.strings:getLocalisedText(campaign_info.description,
776 campaign_info.description_table)
777 campaign_info.winning_text = self.strings:getLocalisedText(campaign_info.winning_text,
778 campaign_info.winning_text_table)
779
780 if self:loadLevel(level_info.path, nil, level_info.name,
781 level_info.map_file, level_info.briefing, nil, _S.errors.load_level_prefix, campaign_info) and self.world then
782 -- The new world needs to know which campaign to continue on.
783 self.world.campaign_info = campaign_info
784
785 -- Play the level advance movie from a position where this campaign will end at 12
786 if campaign_info.movie then
787 local n = math.max(1, 12 - #campaign_info.levels)
788 self.moviePlayer:playAdvanceMovie(n)
789 end
790 end
791 end
792
793 --! Reads the given file name as a Lua chunk from the Campaign folders
794 --! A correct campaign definition contains "name", "description", "levels", and "winning_text".
795 --!param campaign_file (string) Full path of the file to read.
796 --!return (table) Definitions found in the campaign file.
797 function App:readCampaignFile(campaign_file)
798 local chunk, err = loadfile_envcall(campaign_file)
799 if not chunk then
800 return nil, "Error loading " .. campaign_file .. ":\n" .. tostring(err)
801 else
802 local result = {}
803 chunk(result)
804 return result
805 end
806 end
807
808 --! Opens the given file name and returns all Level definitions in a table.
809 --! Values in the returned table: "path", "level_file", "name", "map_file", "briefing", and "end_praise".
810 --!param level (string) Full path or name of the file to read.
811 --!param campaign_dir (string) Folder of the parent campaign file
812 --!return (table) Level info found in the file.
813 function App:readLevelFile(level, campaign_dir)
814 local filename = self:_checkOrFind(level, campaign_dir)
815 local file, err = io.open(filename and filename or "")
816 if not file then
817 return nil, "Could not open the specified level file (" .. level .. "): " .. err
818 end
819 local contents = file:read("*all")
820 file:close()
821
822 local level_info = {}
823 level_info.path = filename
824 level_info.level_file = level
825 level_info.name = contents:match("%Name ?= ?\"(.-)\"") or "Unknown name"
826 local map_file = contents:match("%MapFile ?= ?\"(.-)\"")
827 if not map_file then
828 -- The old way of defining the Map File has been deprecated, but a warning is enough.
829 map_file = contents:match("%LevelFile ?= ?\"(.-)\"")
830 if map_file then
831 print("\nWarning: The level '" .. level_info.name .. "' contains a deprecated variable definition in the level file." ..
832 "'%LevelFile' has been renamed to '%MapFile'. Please advise the map creator to update the level.\n")
833 end
834 level_info.deprecated_variable_used = true
835 end
836 -- Find the full path of the map file, unless it is a CorsixTH additional config or a Theme Hospital map
837 if filename:match(self.level_dir .. "original%d%d%.level") then
838 level_info.map_file = map_file
839 elseif map_file then
840 if map_file:lower():match("^level%.l%d+$") then
841 level_info.map_file = map_file
842 else
843 level_info.map_file = self:_checkOrFind(map_file, campaign_dir)
844 end
845 else
846 return nil, _S.errors.map_file_missing:format(map_file)
847 end
848
849 -- Pick a localised set of briefings, if available
850 local lang_code = self.strings:getLangCode()
851 local local_briefing = contents:match("%LevelBriefingTable%." .. lang_code .. " ?= ?\"(.-)\"")
852 local en_briefing = contents:match("%LevelBriefingTable%.en ?= ?\"(.-)\"")
853 local standard_briefing = contents:match("%LevelBriefing ?= ?\"(.-)\"")
854 level_info.briefing = local_briefing or en_briefing or standard_briefing
855
856 local local_end_praise = contents:match("%LevelDebriefingTable%." .. lang_code .. " ?= ?\"(.-)\"")
857 local en_end_praise = contents:match("%LevelDebriefingTable%.en ?= ?\"(.-)\"")
858 local standard_end_praise = contents:match("%LevelDebriefing ?= ?\"(.-)\"")
859 level_info.end_praise = local_end_praise or en_end_praise or standard_end_praise
860 return level_info
861 end
862
863 --! Searches in the given folders for the given filename
864 --!param search_paths (table) List of folders (strings) to look through
865 --!param filename (string) Filename to search for.
866 --!return path (string) The full path of the found file
867 function App:findFileInDirs(search_paths, filename)
868 for _, parent_path in ipairs(search_paths) do
869 local check_path = parent_path .. filename
870 local file, _ = io.open(check_path, "rb")
871 if file then
872 file:close()
873 return check_path
874 end
875 end
876 end
877
878 --! Invokes a protected call of App:_loadLevel(...). See that function for more information.
879 --! This function should always be called to catch errors and properly pass the
880 --! error to the player
881 --!param error_prefix (string) (Optional) Prefixes the error relevant to what was loaded
882 --! return (boolean) The outcome of the pcall
883 function App:loadLevel(level, difficulty, level_name, level_file, level_intro, map_editor, error_prefix, campaign_info)
884 local status, err = pcall(self._loadLevel, self, level, difficulty, level_name,
885 level_file, level_intro, map_editor, campaign_info)
886 tracy.Message("Loading level: " .. (level_name or level or "map editor"))
887 if not status then
888 err = error_prefix and error_prefix .. err or "Error while loading level: " .. err
889 print(err)
890 self:loadMainMenu() -- We need to unload all level elements that succeeded
891 self.ui:addWindow(UIInformation(self.ui, { err }))
892 end
893 return status
894 end
895
896 --! Private Function to load the level. Call via App:loadLevel(...)
897 --! Loads the specified level.
898 --!param level (string) Full path of a custom level, name of a TH level, or nil for mapeditor
899 --!param difficulty (string) One of "easy, full, hard", or nil for custom levels
900 --!param level_name (string) Display name of the level
901 --!param level_file (string) Full path of a custom map, name of a TH level,
902 -- or nil for TH campaign or mapeditor
903 --!param level_intro (string) Introduction text displayed to the player
904 --!param map_editor (boolean) True for opening the map editor
905 --!param campaign_info (table of strings) Information about campaign in case loading level
906 -- is a part of a campaign. if not part of a campaign then campaign_info is nil.
907 function App:_loadLevel(level, difficulty, level_name, level_file, level_intro, map_editor, campaign_info)
908 if self.world then
909 self:worldExited()
910 end
911
912 -- Check that we can load the data before unloading current map
913 local new_map = Map(self)
914 local map_objects, errors = new_map:load(level, difficulty, level_name, level_file, level_intro, map_editor)
915 if not map_objects then
916 self.ui:addWindow(UIInformation(self.ui, { errors }))
917 return
918 end
919 -- If going from another level, save progress.
920 local campaign_data = self.world and self.world:getCampaignData()
921
922 -- Make sure there is no blue filter active.
923 self.video:setBlueFilterActive(false)
924
925 -- Unload ui, world and map
926 self.ui = nil
927 self.world = nil
928 self.map = nil
929
930 -- Load map
931 self.map = new_map
932 self.map:setBlocks(self.gfx:loadSpriteTable("Data", "VBlk-0"))
933 self.map:setDebugFont(self.gfx:loadFontAndSpriteTable("QData", "Font01V"))
934
935 local function determineFreeBuildMode()
936 local is_main_campaign = tonumber(new_map.level_number)
937 local is_custom_campaign = campaign_info ~= nil
938 return self.config.free_build_mode and not (is_main_campaign or is_custom_campaign)
939 end
940
941 -- Load world
942 self.world = World(self, determineFreeBuildMode())
943 self.world:createMapObjects(map_objects)
944
945 -- Enable / disable SoundEffects
946 self.audio:playSoundEffects(self.config.play_sounds)
947
948 -- Load UI
949 self.ui = GameUI(self, self.world:getLocalPlayerHospital(), map_editor)
950 self.world:setUI(self.ui) -- Function call allows world to set up its keyHandlers
951
952 -- Now restore progress from previous levels.
953 if campaign_data then
954 self.world:setCampaignData(campaign_data)
955 end
956
957 -- Log if we're playing with the demo or full graphics set
958 -- TODO: Adjust for new_gfx set when implemented
959 self.world.gfx_set = self.using_demo_files and "demo" or "full"
960 end
961
962 -- This is a useful debug and development aid
963 function App:dumpStrings()
964 -- Accessors to reach through the userdata proxies on strings
965 local LUT = debug.getregistry().StringProxyValues
966 local function val(o)
967 if type(o) == "userdata" then
968 return LUT[o]
969 else
970 return o
971 end
972 end
973
974 local function is_table(o)
975 return type(val(o)) == "table"
976 end
977
978 local dir = self.command_line["config-file"] or ""
979 dir = string.sub(dir, 0, -11)
980 local fi = assert(io.open(dir .. "debug-strings-orig.txt", "w"))
981 for i, sec in ipairs(_S.deprecated) do
982 for j, str in ipairs(sec) do
983 fi:write("[" .. i .. "," .. j .. "] " .. ("%q\n"):format(val(str)))
984 end
985 fi:write("\n")
986 end
987 fi:close()
988
989 local function dump_by_line(file, obj, prefix)
990 for n, o in pairs(obj) do
991 if n ~= "deprecated" then
992 local new_prefix
993 if type(n) == "number" then
994 new_prefix = prefix .. "[" .. n .. "]"
995 else
996 new_prefix = (prefix == "") and n or (prefix .. "." .. n)
997 end
998 if is_table(o) then
999 dump_by_line(file, o, new_prefix)
1000 else
1001 file:write(new_prefix .. " = " .. "\"" .. val(o) .. "\"\n")
1002 end
1003 end
1004 end
1005 end
1006
1007 local function dump_grouped(file, obj, prefix)
1008 for n, o in pairs(obj) do
1009 if n ~= "deprecated" then
1010 local n1 = type(n) == "number" and "[" .. n .. "]" or n
1011 if is_table(o) then
1012 file:write(prefix .. n1 .. " = {\n")
1013 dump_grouped(file, o, prefix .. " ")
1014 file:write(prefix .. "}")
1015 else
1016 file:write(prefix .. n1 .. " = " .. "\"" .. val(o) .. "\"")
1017 end
1018 if prefix ~= "" then
1019 file:write(",")
1020 end
1021 file:write("\n")
1022 end
1023 end
1024 end
1025
1026 fi = assert(io.open(dir .. "debug-strings-new-lines.txt", "w"))
1027 dump_by_line(fi, _S, "")
1028 fi:close()
1029
1030 fi = assert(io.open(dir .. "debug-strings-new-grouped.txt", "w"))
1031 dump_grouped(fi, _S, "")
1032 fi:close()
1033
1034 self:checkMissingStringsInLanguage(dir, self.config.language)
1035 -- Uncomment these lines to get diffs for all languages in the game
1036 -- for _, lang in pairs(self.strings.languages_english) do
1037 -- self:checkMissingStringsInLanguage(dir, lang)
1038 -- end
1039 print("")
1040 print("------------------------------------------------------")
1041 print("Dumped strings to default configuration file directory")
1042 print("------------------------------------------------------")
1043 print("")
1044 end
1045
1046 --! Compares strings provided by language file of given language WITHOUT inheritance
1047 -- with strings provided by english language with inheritance (i.e. all strings).
1048 -- This will give translators an idea which strings are missing in their translation.
1049 --!param dir The directory where the file to write to should be.
1050 --!param language The language to check against.
1051 function App:checkMissingStringsInLanguage(dir, language)
1052 -- Accessors to reach through the userdata proxies on strings
1053 local LUT = debug.getregistry().StringProxyValues
1054 local function val(o)
1055 if type(o) == "userdata" then
1056 return LUT[o]
1057 else
1058 return o
1059 end
1060 end
1061
1062 local function is_table(o)
1063 return type(val(o)) == "table"
1064 end
1065
1066 local ltc = self.strings.language_to_chunk
1067 if ltc[language] ~= ltc["english"] then
1068 local str_en = self.strings:load("english", true)
1069 local str_cur = self.strings:load(language, true, true)
1070 local function dump_diff(file, obj1, obj2, prefix)
1071 for n, o in pairs(obj1) do
1072 if n ~= "deprecated" then
1073 local new_prefix
1074 if type(n) == "number" then
1075 new_prefix = prefix .. "[" .. n .. "]"
1076 else
1077 new_prefix = (prefix == "") and n or (prefix .. "." .. n)
1078 end
1079 if is_table(o) then
1080 -- if obj2 is already nil (i.e. whole table does not exist in current language), carry over nil
1081 dump_diff(file, o, obj2 and obj2[n], new_prefix)
1082 else
1083 if not (obj2 and obj2[n]) then
1084 -- does not exist in current language
1085 file:write(new_prefix .. " = " .. "\"" .. val(o) .. "\"\n")
1086 end
1087 end
1088 end
1089 end
1090 end
1091
1092 -- if possible, use the English name of the language for the file name.
1093 local language_english = language
1094 for _, lang_eng in pairs(self.strings.languages_english) do
1095 if ltc[language] == ltc[lang_eng:lower()] then
1096 language_english = lang_eng
1097 break
1098 end
1099 end
1100
1101 local fi = assert(io.open(dir .. "debug-strings-diff-" .. language_english:lower() .. ".txt", "w"))
1102 fi:write("------------------------------------\n")
1103 fi:write("MISSING STRINGS IN LANGUAGE \"" .. language:upper() .. "\":\n")
1104 fi:write("------------------------------------\n")
1105 dump_diff(fi, str_en, str_cur, "")
1106 fi:write("------------------------------------\n")
1107 fi:write("SUPERFLUOUS STRINGS IN LANGUAGE \"" .. language:upper() .. "\":\n")
1108 fi:write("------------------------------------\n")
1109 dump_diff(fi, str_cur, str_en, "")
1110 fi:close()
1111 end
1112 end
1113
1114 function App:fixConfig()
1115 for key, value in pairs(self.config) do
1116 -- Trim whitespace from beginning and end string values - it shouldn't be
1117 -- there (at least in any current configuration options).
1118 if type(value) == "string" then
1119 if value:match("^[%s]") or value:match("[%s]$") then
1120 self.config[key] = value:match("^[%s]*(.-)[%s]*$")
1121 end
1122 end
1123
1124 -- For language, make language name lower case
1125 if key == "language" and type(value) == "string" then
1126 self.config[key] = value:lower()
1127
1128 -- For resolution, clamp resolution to at least 640x480
1129 elseif key == "width" and (type(value) ~= "number" or value < App.MIN_WINDOW_WIDTH) then
1130 self.config[key] = App.MIN_WINDOW_WIDTH
1131
1132 elseif key == "height" and (type(value) ~= "number" or value < App.MIN_WINDOW_HEIGHT) then
1133 self.config[key] = App.MIN_WINDOW_HEIGHT
1134
1135 -- For scale, clamp to integer scale >= 1
1136 elseif key == "ui_scale" then
1137 if type(value) == "number" then
1138 self.config[key] = math.max(math.floor(value), 1)
1139 else
1140 self.config[key] = 1
1141 end
1142
1143 elseif (key == "scroll_speed" or key == "shift_scroll_speed") and
1144 type(value) == "number" then
1145 if value > 10 then
1146 self.config[key] = 10
1147 elseif value < 1 then
1148 self.config[key] = 1
1149 end
1150
1151 -- For player name, trim spaces or fill in from environment
1152 elseif key == "player_name" then
1153 value = value:match('^%s*(.*%S)') or "" -- Trim spaces
1154 if value:len() == 0 then -- If empty, use computer user's name,
1155 value = os.getenv("USER") or os.getenv("USERNAME")
1156 end
1157 value = value:match('^%s*(.*%S)') or ""
1158 if value:len() == 0 then -- unless that is also empty
1159 value = "PLAYER"
1160 end
1161 self.config[key] = value
1162 end
1163 end
1164
1165 -- clamp scale to suitable values for current resolution
1166 if self.config.ui_scale * App.MIN_WINDOW_WIDTH > self.config.width or
1167 self.config.ui_scale * App.MIN_WINDOW_HEIGHT > self.config.height then
1168 self.config.ui_scale = math.floor(math.min(
1169 self.config.width / App.MIN_WINDOW_WIDTH,
1170 self.config.height / App.MIN_WINDOW_HEIGHT))
1171 end
1172 end
1173
1174 function App:saveConfig()
1175 local conf_path = self.command_line["config-file"] or "config.txt"
1176 require('config_finder').save_config(conf_path, self.config)
1177 end
1178
1179 --! Tries to open the given file or a file in OS's temp dir.
1180 -- Returns the file handler, and true if it was written to the intended file.
1181 --!param file The full path of the intended file
1182 --!param mode The mode in which the file is opened, defaults to write
1183 function App:writeToFileOrTmp(file, mode)
1184 local f, err = io.open(file, mode or "w")
1185 if err then
1186 local tmp_file = os.tmpname()
1187 f = io.open(tmp_file, mode or "w")
1188 if self.ui then self.ui:addWindow(UIInformation(self.ui,
1189 { _S.errors.save_to_tmp:format(file, tmp_file, err) }))
1190 else
1191 print("Attempt to write to " .. file .. " failed. File was written instead to temporary location " .. tmp_file .. " because of the error: " .. err)
1192 end
1193 end
1194 assert(f, "Error: cannot write to filesystem")
1195 return f, not err
1196 end
1197
1198 function App:fixHotkeys()
1199 for key, value in pairs(self.hotkeys) do
1200 -- Trim whitespace from beginning and end string values - it shouldn't be
1201 -- there (at least in any current configuration options).
1202 if type(value) == "string" then
1203 if value:match("^[%s]") or value:match("[%s]$") then
1204 self.hotkeys[key] = value:match("^[%s]*(.-)[%s]*$")
1205 end
1206 end
1207 end
1208 end
1209
1210 function App:saveHotkeys()
1211 -- Load lines from config file
1212 local hotkeys_filename = self.command_line["hotkeys-file"] or "hotkeys.txt"
1213 require('config_finder').save_hotkeys(hotkeys_filename, self.hotkeys)
1214 end
1215
1216 function App:errorHandler(last_dispatch_type, st)
1217 print("An error has occurred!")
1218 print("Almost anything can be the cause, but the detailed information " ..
1219 "below can help the developers find the source of the error.")
1220 print("Running: The " .. last_dispatch_type .. " handler.")
1221 print("A stack trace is included below, and the handler has been disconnected.")
1222 print(st)
1223 print("")
1224 self.video:setCaptureMouse(false) -- Free the mouse, so the user can eg close the window.
1225 if self.world then
1226 self.world:gameLog("Error in " .. last_dispatch_type .. " handler: ")
1227 self.world:gameLog(st)
1228 self.world:dumpGameLog()
1229 end
1230 if self.world and last_dispatch_type == "timer" and self.world.current_tick_entity then
1231 -- Disconnecting the tick handler is quite a drastic measure, so give
1232 -- the option of just disconnecting the offending entity and attempting
1233 -- to continue.
1234 local handler = self.eventHandlers[last_dispatch_type]
1235 local entity = self.world.current_tick_entity
1236 self.world.current_tick_entity = nil
1237 if class.is(entity, Patient) then
1238 self.ui:addWindow(UIPatient(self.ui, entity))
1239 elseif class.is(entity, Staff) then
1240 self.ui:addWindow(UIStaff(self.ui, entity))
1241 end
1242 self.ui:addWindow(UIConfirmDialog(self.ui, true,
1243 "Sorry, but an error has occurred. There can be many reasons - see the " ..
1244 "log window for details. Would you like to attempt a recovery?",
1245 --[[persistable:app_attempt_recovery]] function()
1246 self.world:gameLog("Recovering from error in timer handler...")
1247 entity.ticks = false
1248 self.eventHandlers.timer = handler
1249 end
1250 ))
1251 end
1252 self.eventHandlers[last_dispatch_type] = nil
1253 if last_dispatch_type ~= "frame" then
1254 -- If it wasn't the drawing code which failed, then it would be useful
1255 -- to ensure that a draw happens, as with events disconnected, a frame
1256 -- might not otherwise be drawn for a while.
1257 pcall(self.drawFrame, self)
1258 end
1259 end
1260
1261 local done_no_handler_warning = {}
1262
1263 function App:dispatch(evt_type, ...)
1264 local handler = self.eventHandlers[evt_type]
1265 if handler then
1266 return handler(self, ...)
1267 else
1268 if not done_no_handler_warning[evt_type] then
1269 print("Warning: No event handler for " .. evt_type)
1270 done_no_handler_warning[evt_type] = true
1271 end
1272 return false
1273 end
1274 end
1275
1276 function App:onTick(...)
1277 if (not self.moviePlayer.playing) then
1278 if self.world then
1279 self.world:onTick(...)
1280 end
1281 self.ui:onTick(...)
1282 end
1283 return true -- tick events always result in a repaint
1284 end
1285
1286 --! Function for handling idle time in the main menu, which leads to playing the
1287 --! demo gameplay trailer if left long enough
1288 function App:idle()
1289 if not self.config.play_demo then return end
1290 -- Check if we are in a proper 'idle' state and solely on the main menu
1291 if not self.ui:getWindowActiveStatus() or not self.ui:getWindow(UIMainMenu) or
1292 self.ui:getWindow(UIUpdate) or self.ui:getWindow(UIConfirmDialog) then
1293 self:resetIdle()
1294 return
1295 end
1296 -- Have we been idle enough (~30s, based on SDL tick rate of 18ms)
1297 if self.idle_tick > 1680 then
1298 -- User is idle, play the demo gameplay movie
1299 self.moviePlayer:playDemoMovie()
1300 self:resetIdle()
1301 else
1302 self.idle_tick = self.idle_tick + 1
1303 end
1304 end
1305
1306 -- Reset the idle count
1307 function App:resetIdle()
1308 self.idle_tick = 0
1309 end
1310
1311 local fps_history = {} -- Used to average FPS over the last thirty frames
1312 for i = 1, 30 do fps_history[i] = 0 end
1313 local fps_sum = 0 -- Sum of fps_history array
1314 local fps_next = 1 -- Used to loop through fps_history when [over]writing
1315
1316 function App:drawFrame()
1317 self.video:startFrame()
1318 if (self.moviePlayer.playing) then
1319 self.key_modifiers = {}
1320 self.moviePlayer:refresh()
1321 else
1322 self.key_modifiers = SDL.getKeyModifiers()
1323 self.ui:draw(self.video)
1324 end
1325 self.video:endFrame()
1326
1327 if self.config.track_fps then
1328 fps_sum = fps_sum - fps_history[fps_next]
1329 fps_history[fps_next] = SDL.getFPS()
1330 fps_sum = fps_sum + fps_history[fps_next]
1331 fps_next = (fps_next % #fps_history) + 1
1332 end
1333 end
1334
1335 function App:getFPS()
1336 if self.config.track_fps then
1337 return fps_sum / #fps_history
1338 end
1339 end
1340
1341 function App:onKeyDown(...)
1342 return self.ui:onKeyDown(...)
1343 end
1344
1345 function App:onKeyUp(...)
1346 return self.ui:onKeyUp(...)
1347 end
1348
1349 function App:onEditingText(...)
1350 return self.ui:onEditingText(...)
1351 end
1352
1353 function App:onTextInput(...)
1354 return self.ui:onTextInput(...)
1355 end
1356
1357 function App:onMouseUp(...)
1358 return self.ui:onMouseUp(...)
1359 end
1360
1361 function App:onMouseDown(...)
1362 return self.ui:onMouseDown(...)
1363 end
1364
1365 function App:onMouseMove(...)
1366 return self.ui:onMouseMove(...)
1367 end
1368
1369 function App:onMouseWheel(...)
1370 return self.ui:onMouseWheel(...)
1371 end
1372
1373 function App:onWindowActive(...)
1374 return self.ui:onWindowActive(...)
1375 end
1376
1377 --! Window has been resized by the user
1378 --! Call the UI to handle the new window size
1379 function App:onWindowResize(...)
1380 return self.ui:onWindowResize(...)
1381 end
1382
1383 function App:onMusicOver(...)
1384 return self.audio:onMusicOver(...)
1385 end
1386
1387 function App:onMovieOver(...)
1388 self.moviePlayer:onMovieOver(...)
1389 end
1390
1391 function App:onSoundOver(...)
1392 return self.audio:onSoundPlayed(...)
1393 end
1394
1395 function App:onMultiGesture(...)
1396 return self.ui:onMultiGesture(...)
1397 end
1398
1399 function App:isThemeHospitalPath(path)
1400 local ngot = 0
1401 for obj, _ in lfs.dir(path) do
1402 for _, thing in ipairs({ "data", "levels", "qdata" }) do
1403 if obj:lower() == thing and
1404 lfs.attributes(path .. pathsep .. obj, "mode") == "directory" then
1405 ngot = ngot + 1
1406 end
1407 end
1408 end
1409 if ngot == 3 then
1410 return true
1411 end
1412 end
1413
1414 function App:checkInstallFolder()
1415 self.fs = FileSystem()
1416 local status, _
1417 if self.config.theme_hospital_install then
1418 status, _ = self.fs:setRoot(self.config.theme_hospital_install)
1419 end
1420 local message = "Please make sure that you point the game to" ..
1421 " a valid copy of the data files from the original game," ..
1422 " as said files are required for graphics and sounds."
1423 if not status then
1424 -- Table of predictable places. First three are platform independent,
1425 -- then macOS app and its parent folder, GOG bundle,
1426 -- then linux Filesystem Hierarchy Standard, then Windows Program Files
1427 -- mac_app_dir is the macOS app base directory named CorsixTH.app
1428 local mac_app_dir = debug.getinfo(1).short_src:match("(.*)/Contents/.")
1429 local user_dir = os.getenv("HOME") or os.getenv("USERPROFILE")
1430 local win_home_dir = nil;
1431 if os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH") then
1432 win_home_dir = os.getenv("HOMEDRIVE") .. os.getenv("HOMEPATH")
1433 if win_home_dir == user_dir then win_home_dir = nil; end
1434 end
1435 local possible_locations = {
1436 user_dir,
1437 user_dir and (user_dir .. pathsep .. "Documents"),
1438 win_home_dir,
1439 corsixth.require("config_finder").config_filename:match("(.*[/\\])"):sub(1, -2),
1440 mac_app_dir,
1441 mac_app_dir and mac_app_dir:match("(.*)/.*%.app"),
1442 "/Applications/Theme Hospital.app/Contents/Resources/game/Theme Hospital.app/" ..
1443 "Contents/Resources/Theme Hospital.boxer/C.harddisk",
1444 "/usr/share/games/corsix-th",
1445 "/usr/local/share/games/corsix-th",
1446 os.getenv("ProgramFiles"),
1447 os.getenv("ProgramFiles(x86)"),
1448 [[C:]], [[D:]], [[E:]], [[F:]], [[G:]], [[H:]] }
1449 local possible_folders = { "ThemeHospital", "Theme Hospital", "HOSP", "TH97",
1450 [[GOG Galaxy\Games\Theme Hospital]], [[GOG.com\Theme Hospital]],
1451 [[GOG Games\Theme Hospital]], [[Origin Games\Theme Hospital\data\Game]],
1452 [[EA Games\Theme Hospital\data\Game]]
1453 }
1454 for _, dir in pairs(possible_locations) do
1455 if status then break end
1456 for _, folder in pairs(possible_folders) do
1457 local _
1458 local path = dir .. pathsep .. folder
1459 if lfs.attributes(path, "mode") == "directory" and self:isThemeHospitalPath(path) then
1460 print("Game data found at: " .. path)
1461 print("This will be written to the config file")
1462 self.config.theme_hospital_install = path
1463 status, _ = self.fs:setRoot(path)
1464 break
1465 end
1466 end
1467 end
1468 if not status then
1469 -- If the given directory didn't exist, then likely the config file hasn't
1470 -- been changed at all from the default, and we looked unsuccessfully in
1471 -- some likely folders for the game data, so we continue to initialise the
1472 -- app, and give the user a dialog asking for the correct directory.
1473 return false
1474 end
1475 end
1476
1477 -- Check that a few core files are present
1478 local missing = {}
1479 local function check(path)
1480 if not self.fs:readContents(path) then
1481 missing[#missing + 1] = path
1482 end
1483 end
1484
1485 check("Data" .. pathsep .. "VBlk-0.tab")
1486 check("Levels" .. pathsep .. "Level.L1")
1487 check("QData" .. pathsep .. "SPointer.dat")
1488 if #missing ~= 0 then
1489 missing = table.concat(missing, ", ")
1490 message = "Invalid Theme Hospital folder specified in config file, " ..
1491 "as at least the following files are missing: " .. missing .. ".\n" ..
1492 message
1493 print(message)
1494 print("Trying to let the user select a new one.")
1495 return false, { message }
1496 end
1497
1498 -- Check for demo version
1499 if self.fs:readContents("DataM", "Demo.dat") then
1500 self.using_demo_files = true
1501 print("Notice: Using data files from demo version of Theme Hospital.")
1502 print("Consider purchasing a full copy of the game to support EA.")
1503 end
1504
1505 -- Do a few more checks to make sure that commonly corrupted files are OK.
1506 local corrupt = {}
1507
1508 -- Check for file corruption for local files.
1509 -- No check is done if the game is loaded from an ISO
1510 local function check_corrupt(path, correct_size, allow_missing)
1511 -- If the file exists but is smaller than usual it is probably corrupt
1512 if self.fs:fileExists(path) then
1513 local real_size = self.fs:fileSize(path)
1514 if real_size + 1024 < correct_size or real_size - 1024 > correct_size then
1515 corrupt[#corrupt + 1] = path .. " (Size: " .. math.floor(real_size / 1024) .. " kB / Correct: about " .. math.floor(correct_size / 1024) .. " kB)"
1516 end
1517 elseif not allow_missing then
1518 corrupt[#corrupt + 1] = path .. " (This file is missing)"
1519 end
1520 end
1521
1522 if self.using_demo_files then
1523 check_corrupt("ANIMS" .. pathsep .. "WINLEVEL.SMK", 243188, true)
1524 check_corrupt("LEVELS" .. pathsep .. "LEVEL.L1", 163948)
1525 check_corrupt("DATA" .. pathsep .. "BUTTON01.DAT", 252811)
1526 else
1527 check_corrupt("ANIMS" .. pathsep .. "AREA01V.SMK", 251572, true)
1528 check_corrupt("ANIMS" .. pathsep .. "WINGAME.SMK", 2066656, true)
1529 check_corrupt("ANIMS" .. pathsep .. "WINLEVEL.SMK", 335220, true)
1530 check_corrupt("INTRO" .. pathsep .. "INTRO.SM4", 33616520, true)
1531 check_corrupt("ANIMS" .. pathsep .. "LOSE1.SMK", 1009728, true)
1532 end
1533
1534 if #corrupt ~= 0 then
1535 table.insert(corrupt, 1, "There appears to be corrupt files in your Theme Hospital folder, " ..
1536 "so don't be surprised if CorsixTH crashes. At least the following files are wrong:")
1537 table.insert(corrupt, message)
1538 end
1539
1540 local fontData = assert(self.fs:readContents("QData" .. pathsep .. "Font00V.dat"))
1541 local fontcrc = TH.CRC32File(fontData)
1542
1543 local charset
1544 if fontcrc == 0x0033FA05 then
1545 charset = "mik"
1546 else
1547 charset = "cp437"
1548 end
1549
1550 return true, #corrupt ~= 0 and corrupt or nil, charset
1551 end
1552
1553 function App:findSoundFont()
1554 local data_dir = self:getFullPath()
1555
1556 local possible_locations = {
1557 self.config.soundfont or false,
1558 data_dir .. "FluidR3_GM.sf2",
1559 data_dir .. "FluidR3.sf3",
1560 "/usr/share/soundfonts/default.sf2", -- default linux
1561 "/usr/share/sounds/sf2/FluidR3_GM.sf2", -- debian based
1562 "/usr/share/soundfonts/FluidR3_GM.sf2" -- archlinux and others
1563 }
1564
1565 for _, sf_path in ipairs(possible_locations) do
1566 if sf_path and lfs.attributes(sf_path) then
1567 return sf_path
1568 end
1569 end
1570
1571 return nil
1572 end
1573
1574 --! Get the directory containing the bitmap files.
1575 --!return Name of the directory containing the bitmap files, ending with a
1576 -- directory path separator.
1577 function App:getBitmapDir()
1578 return (self.command_line["bitmap-dir"] or "Bitmap") .. pathsep
1579 end
1580
1581 -- Load bitmap data into memory.
1582 --!param filename Name of the file to load.
1583 --!return The loaded data.
1584 function App:readBitmapDataFile(filename)
1585 filename = self:getBitmapDir() .. filename
1586 local file = assert(io.open(filename, "rb"))
1587 local data = file:read("*a")
1588 file:close()
1589 if data:sub(1, 3) == "RNC" then
1590 data = assert(rnc.decompress(data))
1591 end
1592 return data
1593 end
1594
1595 -- Read a data file of the application into memory (possibly with decompression).
1596 --!param dir (string) Directory to read from. "Bitmap" and "Levels" are
1597 -- meta-directories, and get resolved to real directories in the function.
1598 --!param filename (string or nil) If specified, the file to load. If 'nil', the
1599 -- 'dir' parameter is the filename in the "Data" directory.
1600 function App:readDataFile(dir, filename)
1601 if dir == "Bitmap" then
1602 return self:readBitmapDataFile(filename)
1603 elseif dir == "Levels" then
1604 return self:readMapDataFile(filename)
1605 end
1606 if filename == nil then
1607 dir, filename = "Data", dir
1608 end
1609
1610 local data = assert(self.fs:readContents(dir .. pathsep .. filename))
1611 if data:sub(1, 3) == "RNC" then
1612 data = assert(rnc.decompress(data))
1613 end
1614 return data
1615 end
1616
1617 --! Get a level file.
1618 --!param path (string) Full path of the level file, or a Theme Hospital level filename
1619 --!return If the file could be found, the data of the file, else a
1620 -- tuple 'nil', and an error description
1621 function App:readMapDataFile(path)
1622 local data
1623 if path:match(pathsep) then
1624 local file = io.open(path, "rb")
1625 if file then
1626 data = file:read("*a")
1627 file:close()
1628 end
1629 else
1630 data = self.fs:readContents("Levels" .. pathsep .. path)
1631 if not data then
1632 return nil, _S.errors.missing_th_data_file:format(path)
1633 end
1634 end
1635 if data then
1636 if data:sub(1, 3) == "RNC" then
1637 data = assert(rnc.decompress(data))
1638 end
1639 else
1640 -- Could not find the file
1641 return nil, _S.errors.map_file_missing:format(path)
1642 end
1643 return data
1644 end
1645
1646 function App:loadLuaFolder(dir, no_results, append_to)
1647 if dir:sub(-1) ~= pathsep then dir = dir .. pathsep end
1648 local path = self:getFullPath({"Lua", dir}, true)
1649 local results = no_results and "" or (append_to or {})
1650
1651 for file in lfs.dir(path) do
1652 if file:match("%.lua$") then
1653 local status, result = pcall(corsixth.require, dir .. file:sub(1, -5))
1654 if not status then
1655 print("Error loading " .. dir .. file .. ":\n" .. tostring(result))
1656 else
1657 if result == nil then
1658 if not no_results then
1659 print("Warning: " .. dir .. file .. " returned no value")
1660 end
1661 else
1662 if no_results then
1663 print("Warning: " .. dir .. file .. " returned a value:", result)
1664 else
1665 if type(result) == "table" and result.id then
1666 results[result.id] = result
1667 elseif type(result) == "function" then
1668 results[file:match("(.*)%.")] = result
1669 end
1670 results[#results + 1] = result
1671 end
1672 end
1673 end
1674 end
1675 end
1676 if no_results then
1677 return
1678 else
1679 return results
1680 end
1681 end
1682
1683 --[[
1684 CorsixTH versioning follows a convention similar to semantic versioning but it
1685 does not accurately follow its standard. As we are currently <1.0.0 the major
1686 integer is not at play. Instead:
1687 Minor - denotes an new milestone of the program that often encompassses multiple
1688 patches that could break savegames without in-situ afterLoads
1689 Revision - denotes a revised hotfix release of the program that patches a major
1690 bug before the next milestone. The bug is then patched for the next milestone.
1691 Moving forward, revisions should have a savegame_version bump of 1, as 10
1692 savegame versions are reserved each release for patching.
1693 All beta versions must have a savegame increment each time
1694 Each patch note must begin with a '-'
1695 --]]
1696 local release_table = {
1697 -- Format: major, minor, revision, patch (string), savegame_version
1698 {major = 0, minor = 0, revision = 8, patch = "", version = 0}, -- Beta 8 or below
1699 {major = 0, minor = 1, revision = 0, patch = "", version = 51},
1700 {major = 0, minor = 10, revision = 0, patch = "", version = 53},
1701 {major = 0, minor = 11, revision = 0, patch = "", version = 54},
1702 {major = 0, minor = 20, revision = 0, patch = "", version = 66},
1703 {major = 0, minor = 21, revision = 0, patch = "", version = 72},
1704 {major = 0, minor = 30, revision = 0, patch = "", version = 78},
1705 {major = 0, minor = 40, revision = 0, patch = "", version = 91},
1706 {major = 0, minor = 50, revision = 0, patch = "", version = 105},
1707 {major = 0, minor = 60, revision = 0, patch = "", version = 111},
1708 {major = 0, minor = 61, revision = 0, patch = "", version = 122},
1709 {major = 0, minor = 62, revision = 0, patch = "", version = 127},
1710 {major = 0, minor = 63, revision = 0, patch = "", version = 134},
1711 {major = 0, minor = 64, revision = 0, patch = "", version = 138},
1712 {major = 0, minor = 65, revision = 0, patch = "", version = 156},
1713 -- There was also 0.65.1, not differentiated by version number
1714 {major = 0, minor = 66, revision = 0, patch = "", version = 170},
1715 {major = 0, minor = 67, revision = 0, patch = "", version = 180},
1716 {major = 0, minor = 68, revision = 0, patch = "", version = 194},
1717 {major = 0, minor = 69, revision = 0, patch = "-beta1", version = 216},
1718 {major = 0, minor = 69, revision = 0, patch = "-beta2", version = 218},
1719 {major = 0, minor = 69, revision = 0, patch = "-rc1", version = 219},
1720 {major = 0, minor = 69, revision = 0, patch = "", version = 220},
1721 {major = 0, minor = 69, revision = 1, patch = "", version = 221},
1722 {major = 0, minor = 69, revision = 2, patch = "", version = 222},
1723 {major = 0, minor = 70, revision = 0, patch = "-beta1", version = 247},
1724 {major = 0, minor = 70, revision = 0, patch = "-beta2", version = 248},
1725 {major = 0, minor = 70, revision = 0, patch = "-rc1", version = 251},
1726 {major = 0, minor = 70, revision = 0, patch = "-rc2", version = 252},
1727 {major = 0, minor = 70, revision = 0, patch = "", version = 253},
1728 }
1729
1730 --! Retrieve the current savegame version as defined in the application.
1731 function App:getCurrentVersion()
1732 return self.savegame_version
1733 end
1734
1735 --! Requests data regarding a given savegame version
1736 --!param savegame_version (number) What to lookup, uses application version if blank
1737 --!return the matching release table entry
1738 -- If no releases match it returns the base release with the savegame version
1739 -- inserted
1740 function App:getReleaseData(savegame_version)
1741 savegame_version = savegame_version or self:getCurrentVersion()
1742 local release_data
1743 for i = #release_table, 1, -1 do
1744 local release = release_table[i]
1745 if release.version == savegame_version then
1746 release_data = release
1747 break
1748 elseif (release.version - savegame_version) < 0 then
1749 -- we're not on a release version
1750 local develop = shallow_clone(release) -- prevent recursion
1751 develop.version = savegame_version
1752 develop.patch = release.patch .. "-dev" .. savegame_version
1753 release_data = develop
1754 break
1755 end
1756 end
1757 return release_data
1758 end
1759
1760 --! Provides the release (or development) string for a given savegame version
1761 --!param savegame_version (number) The version to look up
1762 --!return A string in the format "v<major>.<minor>.<revision>[patch]"
1763 --! For development builds, the savegame version is appended as a patch e.g. 'dev213'
1764 function App:getReleaseString(savegame_version)
1765 local release = self:getReleaseData(savegame_version)
1766 local release_string = "v" .. release.major .. "." .. release.minor .. "." ..
1767 release.revision
1768 release_string = release_string .. release.patch
1769 return release_string
1770 end
1771
1772 --! Reports a difference between two versions based on requested methodology.
1773 --!param version_a (number or table) The first (usually newer) version to test
1774 --!param version_b (number or table) The second (usually older) version to test
1775 --!param method (string) What method to compare by
1776 --- method(release) reports the difference between the matching releases in steps,
1777 --- revisions are not counted.
1778 --- For development builds it will use the base release it started from when using
1779 --- the release method
1780 --- method(version) reports the difference between two savegame versions
1781 --!return The step difference between release a and release b for release method
1782 --- or The raw savegame version difference for version method
1783 function App:compareVersions(version_a, version_b, method)
1784 assert(type(version_a) == "table" or type(version_a) == "number",
1785 "version_a requires savegame version or an entry from the version table to compare")
1786 assert(type(version_b) == "table" or type(version_b) == "number",
1787 "version_b requires savegame version or an entry from the version table to compare")
1788 assert(method == "release" or method == "version",
1789 "Not using a valid compare method")
1790
1791 if method == "release" then
1792 local function countBackward(version_to_check)
1793 local step = 0
1794 for i = #release_table, 1, -1 do
1795 local release = release_table[i]
1796 if release.version == version_to_check then
1797 break
1798 elseif (release.version - version_to_check) < 0 then
1799 -- we're not on a release version
1800 if step == 0 then step = 1 break end -- working from current development
1801 break
1802 end
1803 if release.revision == 0 and release.patch == "" then
1804 step = step - 1
1805 end
1806 end
1807 return step
1808 end
1809
1810 if type(version_a) == "number" then version_a = self:getReleaseData(version_a) end
1811 if type(version_b) == "number" then version_b = self:getReleaseData(version_b) end
1812 return countBackward(version_a.version) - countBackward(version_b.version)
1813 end
1814
1815 if method == "version" then
1816 local a = version_a.version or version_a
1817 local b = version_b.version or version_b
1818 return a - b
1819 end
1820 end
1821
1822
1823 function App:save(filename)
1824 return SaveGameFile(filename)
1825 end
1826
1827 -- Omit the usual file extension so this file cannot be seen from the normal load and save screen and cannot be overwritten
1828 function App:quickSave()
1829 local filename = "quicksave.qs"
1830 return SaveGameFile(self.savegame_dir .. filename)
1831 end
1832
1833 function App:load(filepath)
1834 tracy.Message("Loading game from " .. filepath)
1835 if self.world then
1836 self:worldExited()
1837 end
1838 return LoadGameFile(filepath)
1839 end
1840
1841 function App:quickLoad()
1842 local filename = "quicksave.qs"
1843 if lfs.attributes(self.savegame_dir .. filename) then
1844 self:load(self.savegame_dir .. filename)
1845 else
1846 self:quickSave()
1847 self.ui:addWindow(UIInformation(self.ui, { _S.errors.load_quick_save }))
1848 end
1849 end
1850
1851 --! Function to check the loaded game is compatible with the program
1852 --!param save_version (num)
1853 --!param gfx_set (string) What graphics set is used
1854 --!return true if compatible, otherwise false
1855 function App:checkCompatibility(save_version, gfx_set)
1856 local app_version = self.savegame_version
1857 local err
1858
1859 -- First check the graphics set matches with the game files
1860 if (gfx_set == "demo" and not self.using_demo_files) then
1861 err = _S.errors.compatibility_error.demo_in_full
1862 elseif (gfx_set == "full" and self.using_demo_files) then
1863 err = _S.errors.compatibility_error.full_in_demo
1864
1865 -- if that's all good, check the save and app version
1866 elseif app_version >= save_version or self.config.debug then
1867 return true
1868 else -- savegame newer than application
1869 err = _S.errors.compatibility_error.new_in_old
1870 end
1871
1872 UILoadGame:loadError(err)
1873 return false
1874 end
1875
1876 --! Check that a file at a full path exists, or find it, or expand filename to full paths
1877 --!param test_file (string) A full path or a filename of a level or map file
1878 --!return (string) A full path that exists
1879 function App:_checkOrFind(test_file, campaign_dir)
1880 -- Check if test_file is a full path (file in a subfolder)
1881 local folder_name, filename = test_file:match(".+[\\/](.+)[\\/](.+)")
1882 local partial_folder, partial_file = test_file:match("(.+)[\\/](.+)")
1883 if folder_name and folder_name:len() > 0 then
1884 -- Full path to the file is known, check file is present
1885 local file_handler, _ = io.open(test_file)
1886 if file_handler then
1887 file_handler:close()
1888 return test_file
1889 end
1890 -- File not found, prepare to search with the found filename
1891 test_file = filename
1892 -- Add path separator of current computer
1893 folder_name = folder_name .. pathsep
1894 elseif partial_folder and partial_file then
1895 -- A partial path is known
1896 folder_name, test_file = partial_folder, partial_file
1897 else
1898 folder_name = ""
1899 end
1900 -- Filename, and possibly folder name, are known, search for file
1901 local level = self.map and self.map.level_number:match("(.+[\\/])") or ""
1902 local campaign_folder = (self.world and self.world.campaign_info and self.world.campaign_info.folder) or ""
1903 local search_paths = {
1904 -- The folder of the campaign or level file, if known
1905 campaign_dir or campaign_folder,
1906 level,
1907 self.user_campaign_dir .. folder_name,
1908 self.user_campaign_dir,
1909 self.user_level_dir,
1910 self.campaign_dir .. folder_name,
1911 self.campaign_dir,
1912 self.level_dir,
1913 }
1914 return self:findFileInDirs(search_paths, test_file)
1915 end
1916
1917 --! Restarts the current level (offers confirmation window first)
1918 --!param message (string) Optional message to the player
1919 function App:restart(message)
1920 assert(self.map, "Trying to restart while no map is loaded.")
1921 self.ui:addWindow(UIConfirmDialog(self.ui, true, message or _S.confirmation.restart_level,
1922 --[[persistable:app_confirm_restart]] function()
1923 self:worldExited()
1924 local campaign_info = self.world.campaign_info
1925 local level = self.map.level_filename or self.map.level_number
1926 local difficulty = self.map.difficulty
1927 local name, file, intro = self.map.level_name, self.map.map_file, self.map.level_intro
1928 if tonumber(level) then -- TH campaign
1929 self:loadLevel(level, difficulty, name, file, intro, nil, _S.errors.load_level_prefix, campaign_info)
1930 return
1931 end
1932 level = self:_checkOrFind(level)
1933 if not file:match("^LEVEL%.L%d") then -- Map file might be a TH map filename
1934 file = self:_checkOrFind(file)
1935 end
1936 if level and file then
1937 self:loadLevel(level, difficulty, name, file, intro, nil, _S.errors.load_level_prefix, campaign_info)
1938 else
1939 self.ui:addWindow(UIInformation(self.ui, { _S.errors.cannot_restart_missing_files
1940 :format(self.map.level_number, self.map.map_file) }))
1941 end
1942 end))
1943 end
1944
1945 --! Begin the map editor
1946 function App:mapEdit()
1947 self:loadLevel("", nil, nil, nil, nil, true, _S.errors.load_map_prefix, nil)
1948 end
1949
1950 --! Exits the game completely (no confirmation window)
1951 function App:exit()
1952 -- Save config before exiting
1953 self:saveConfig()
1954 self:saveHotkeys()
1955 SDL.quit()
1956 end
1957
1958 --! Exits the game completely without saving the config i.e. Alt+F4 for Quit Application
1959 function App:abandon()
1960 SDL.quit()
1961 end
1962
1963 function App:reset()
1964 debug.getregistry()._RESTART = true
1965 SDL.quit()
1966 end
1967
1968 --! This function is automatically called after loading a game and serves for compatibility.
1969 function App:afterLoad()
1970 self.ui:addOrRemoveDebugModeKeyHandlers()
1971 local old = self.world.savegame_version or 0
1972 local new = self.savegame_version
1973
1974 if old == 0 then
1975 -- Game log was not present before introduction of savegame versions, so create it now.
1976 self.world.game_log = {}
1977 self.world:gameLog("Created Gamelog on load of old (pre-versioning) savegame.")
1978 end
1979 if not self.world.original_savegame_version then
1980 self.world.original_savegame_version = old
1981 end
1982 local first = self.world.original_savegame_version
1983
1984 -- Generate the human-readable version number (old [loaded save], new [program], first [original])
1985 local first_version = first .. " (" .. self:getReleaseString(first) .. ")"
1986 local old_version = old .. " (" .. self:getReleaseString(old) .. ")"
1987 local new_version = new .. " (" .. self:getReleaseString(new) .. ")"
1988
1989 if new == old then
1990 local msg_same = "Savegame version is %s, originally it was %s."
1991 self.world:gameLog(msg_same:format(new_version, first_version))
1992 self.world:playLoadedEntitySounds()
1993 elseif new > old then
1994 local msg_older = "Savegame changed from %s to %s. The save was created using %s."
1995 self.world:gameLog(msg_older:format(old_version, new_version, first_version))
1996 else -- Save is newer than the game and can only proceed in debug mode
1997 local get_old_release_version = self.world.release_version or "Trunk" -- For compatibility
1998 old_version = old .. " (" .. get_old_release_version .. ")"
1999 local msg_newer = "Warning: loaded savegame version %s in older version %s."
2000 self.world:gameLog(msg_newer:format(old_version, new_version))
2001 self.ui:addWindow(UIInformation(self.ui, { _S.warnings.newersave }))
2002 end
2003 self.world.release_version = self:getReleaseString(new)
2004 self.world.savegame_version = new
2005
2006 if old < 87 then
2007 local new_object = corsixth.require("objects.gates_to_hell")
2008 Object.processTypeDefinition(new_object)
2009 self.objects[new_object.id] = new_object
2010 self.world:newObjectType(new_object)
2011 end
2012
2013 if old < 114 then
2014 local rathole_type = corsixth.require("objects.rathole")
2015 Object.processTypeDefinition(rathole_type)
2016 self.objects[rathole_type.id] = rathole_type
2017 self.world:newObjectType(rathole_type)
2018 end
2019
2020 --[[Information only:
2021 if old < 166 then
2022 Graphics set type was introduced at this version.
2023 Nothing to do here as it is handled by persistance.
2024 However, it introduces compatibility limitations between the demo and full game
2025 and should be noted.
2026 end
2027 ]] --
2028
2029 self.map:afterLoad(old, new)
2030 self.ui:afterLoad(old, new)
2031 self.world:afterLoad(old, new)
2032 end
2033
2034 --! Runs a comparison between the current (installed) version and the reported
2035 --! update table hosted by Github. If the update table is newer, it will generate
2036 --! an update window.
2037 --! As pre-releases are not announced on the update table, the checker also assumes
2038 --! that any current version with a patch in its name (Beta, RC, etc) will be older
2039 --! than the update table's version if their major, minor, and revision components match.
2040 function App:checkForUpdates()
2041 -- Only check for updates once per application launch
2042 if not self.check_for_updates or not self.config.check_for_updates then return end
2043 self.check_for_updates = false
2044
2045 -- Default language to use for the changelog if no localised version is available
2046 local default_language = "en"
2047 local current_version = self:getReleaseString()
2048
2049 -- Only check for updates against released versions
2050 if string.find(current_version, "dev") then
2051 print("Will not check for updates since this is a development version.")
2052 return
2053 end
2054
2055 print("Checking for CorsixTH updates...")
2056 local update_body, err = TH.FetchLatestVersionInfo()
2057
2058 if not update_body then
2059 print("Couldn't check for updates: " .. err)
2060 return
2061 end
2062
2063 local update_table = loadstring_envcall(update_body, "@updatechecker") {}
2064 update_table.revision = update_table.revision or 0
2065 local changelog = update_table["changelog_" .. default_language]
2066 local new_version = update_table.major .. '.' .. update_table.minor .. '.' .. update_table.revision
2067
2068 -- Semantic version comparison of the current and update version numbers
2069 -- A return value of true means the current version is newer
2070 local function compare_versions()
2071 local current_major, current_minor, current_revision, current_patch =
2072 string.match(current_version, "(%d+)%.(%d+)%.?(%d*) ?(.*)")
2073 current_major, current_minor = tonumber(current_major), tonumber(current_minor)
2074 if current_major > update_table.major then return true
2075 elseif current_major < update_table.major then return false
2076 end
2077 if current_minor > update_table.minor then return true
2078 elseif current_minor < update_table.minor then return false
2079 end
2080
2081 current_revision = tonumber(current_revision) or 0
2082 current_patch = string.len(current_patch) > 0 and current_patch
2083 if current_patch then return current_revision > update_table.revision end
2084 return current_revision >= update_table.revision
2085 end
2086 if compare_versions() then
2087 print("You are running the latest version of CorsixTH.")
2088 return
2089 end
2090
2091 -- Check to make sure download URL is trusted
2092 local download_url = update_table.download_url
2093 local trusted_url = false
2094 local trusted_prefixes = { 'https://corsixth.com/', 'https://github.com/', 'https://corsixth.github.io/' }
2095
2096 for _, v in ipairs(trusted_prefixes) do
2097 if download_url:sub(1, #v) == v then
2098 trusted_url = true
2099 break
2100 end
2101 end
2102 if not trusted_url then
2103 print("Update download url is not on the trusted domains list (" .. download_url .. ")")
2104 return
2105 end
2106
2107 -- Check to see if there's a changelog in the user's language
2108 local current_langs = self.strings:getLanguageNames(self.config.language)
2109 for _, v in ipairs(current_langs) do
2110 if (update_table["changelog_" .. v]) then
2111 changelog = update_table["changelog_" .. v]
2112 break
2113 end
2114 end
2115
2116 print("New version found: " .. new_version)
2117 -- Display the update window
2118 self.ui:addWindow(UIUpdate(self.ui, current_version, new_version, changelog, download_url))
2119 end
2120
2121 -- Free up / stop any resources relying on the current video object
2122 function App:prepareVideoUpdate()
2123 self.video:endFrame()
2124 self.moviePlayer:deallocatePictureBuffer()
2125 end
2126
2127 -- Update / start any resources relying on a video object
2128 function App:finishVideoUpdate()
2129 self.gfx:updateTarget(self.video)
2130 self.moviePlayer:updateRenderer()
2131 self.moviePlayer:allocatePictureBuffer()
2132 self.video:startFrame()
2133 end
2134
2135 function App:isUpdateCheckDisabledByConfig()
2136 return TH.GetCompileOptions().update_check and not self.config.check_for_updates
2137 end
2138
2139 function App:isUpdateCheckAvailable()
2140 return TH.GetCompileOptions().update_check
2141 end
2142
2143 --! Generate information about user's system and the program
2144 --!return System and program info as a string
2145 function App:gamelogHeader()
2146 local compile_opts = TH.GetCompileOptions()
2147 local comp_details = {}
2148 for key, value in pairs(compile_opts) do
2149 table.insert(comp_details, key .. ": " .. tostring(value))
2150 end
2151 table.sort(comp_details)
2152 local compiled = string.format("Compiled with %s\nSDL renderer: %s\n",
2153 table.concat(comp_details, ", "), self.video:getRendererDetails())
2154 local running = string.format("%s run with api version: %s, game version: %s, savegame version: %s\n",
2155 compile_opts.jit or _VERSION, tostring(corsixth.require("api_version")),
2156 self:getReleaseString(), tostring(SAVEGAME_VERSION))
2157 return (compiled .. running)
2158 end
2159
2160 -- Do not remove, for savegame compatibility < r1891
2161 local app_confirm_quit_stub = --[[persistable:app_confirm_quit]] function()
2162 end