Debian Codegraph @

src/Main/fg_init.cxx

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * SPDX-FileName: fg_init.cxx
3 * SPDX-FileComment: FlightGear top level initialization routines
4 * SPDX-FileCopyrightText: Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include <config.h>
9
10 #include <simgear/compiler.h>
11
12 #include <cstdio>
13 #include <cstdlib>
14 #include <cstring> // strcmp()
15
16 #if defined(SG_WINDOWS)
17 #define _WINSOCKAPI_
18 # include <io.h> // isatty()
19 # include <process.h> // _getpid()
20 # include <Windows.h>
21 # define isatty _isatty
22 #else
23 // for open() and options
24 # include <sys/types.h>
25 # include <sys/stat.h>
26 # include <fcntl.h>
27 # include <sys/file.h>
28 #endif
29
30 #include <string>
31
32 #include <osgViewer/Viewer>
33
34 #include <simgear/canvas/Canvas.hxx>
35 #include <simgear/constants.h>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/debug/LogCallback.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/structure/event_mgr.hxx>
40 #include <simgear/structure/SGPerfMon.hxx>
41 #include <simgear/misc/sg_path.hxx>
42 #include <simgear/misc/sg_dir.hxx>
43 #include <simgear/io/iostreams/sgstream.hxx>
44 #include <simgear/misc/strutils.hxx>
45 #include <simgear/embedded_resources/EmbeddedResourceManager.hxx>
46 #include <simgear/props/props_io.hxx>
47 #include <simgear/scene/tsync/terrasync.hxx>
48 #include <simgear/timing/sg_time.hxx>
49
50 #include <simgear/scene/material/Effect.hxx>
51 #include <simgear/scene/material/matlib.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/model/particles.hxx>
54 #include <simgear/scene/tgdb/TreeBin.hxx>
55 #include <simgear/scene/tgdb/userdata.hxx>
56 #include <simgear/scene/tgdb/VPBTechnique.hxx>
57 #include <simgear/scene/tsync/terrasync.hxx>
58
59 #include <simgear/package/Root.hxx>
60 #include <simgear/package/Package.hxx>
61 #include <simgear/package/Install.hxx>
62 #include <simgear/package/Catalog.hxx>
63
64 #include <Add-ons/AddonManager.hxx>
65 #include <Aircraft/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Aircraft/FlightHistory.hxx>
68 #include <Aircraft/initialstate.hxx>
69
70 #include <Airports/runways.hxx>
71 #include <Airports/airport.hxx>
72 #include <Airports/dynamics.hxx>
73 #include <Airports/airportdynamicsmanager.hxx>
74
75 #include <ATC/atc_mgr.hxx>
76
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/autopilotgroup.hxx>
79
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
82
83 #include <Canvas/canvas_mgr.hxx>
84 #include <Canvas/gui_mgr.hxx>
85 #include <Canvas/FGCanvasSystemAdapter.hxx>
86 #include <GUI/new_gui.hxx>
87 #include <GUI/Highlight.hxx>
88 #include <GUI/MessageBox.hxx>
89 #include <Input/input.hxx>
90 #include <Instrumentation/instrument_mgr.hxx>
91 #include <Model/acmodel.hxx>
92 #include <Model/modelmgr.hxx>
93 #include <AIModel/submodel.hxx>
94 #include <AIModel/AIManager.hxx>
95 #include <AIModel/performancedb.hxx>
96 #include <Main/locale.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/SceneryPager.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/voice.hxx>
103 #include <Sound/soundmanager.hxx>
104 #include <Systems/system_mgr.hxx>
105 #include <Time/tide.hxx>
106 #include <Time/light.hxx>
107 #include <Time/TimeManager.hxx>
108
109 #include <Traffic/TrafficMgr.hxx>
110 #include <MultiPlayer/multiplaymgr.hxx>
111 #if defined(ENABLE_SWIFT)
112 #include <Network/Swift/swift_connection.hxx>
113 #endif
114 #include <Cockpit/cockpitDisplayManager.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Environment/ephemeris.hxx>
117 #include <FDM/fdm_shell.hxx>
118 #ifdef ENABLE_HUD
119 #include <Instrumentation/HUD/HUD.hxx>
120 #endif
121 #include <Navaids/NavDataCache.hxx>
122 #include <Network/DNSClient.hxx>
123 #include <Network/HTTPClient.hxx>
124 #include <Network/fgcom.hxx>
125 #include <Network/http/httpd.hxx>
126 #include <Viewer/CameraGroup.hxx>
127 #include <Viewer/FGEventHandler.hxx>
128 #include <Viewer/GraphicsPresets.hxx>
129 #include <Viewer/VRManager.hxx>
130 #include <Viewer/renderer.hxx>
131 #include <Viewer/splash.hxx>
132 #include <Viewer/viewmgr.hxx>
133
134 #include "fg_init.hxx"
135 #include "fg_io.hxx"
136 #include "fg_commands.hxx"
137 #include "fg_props.hxx"
138 #include "FGInterpolator.hxx"
139 #include "options.hxx"
140 #include "globals.hxx"
141 #include "logger.hxx"
142 #include "main.hxx"
143 #include "positioninit.hxx"
144 #include "util.hxx"
145 #include "AircraftDirVisitorBase.hxx"
146
147 #include <Main/ErrorReporter.hxx>
148 #include <Main/MultipleInstanceLock.hxx>
149 #include <Main/sentryIntegration.hxx>
150
151 #include "cJSON.h"
152
153 #if defined(SG_MAC)
154 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
155 #endif
156
157 using std::string;
158 using std::endl;
159 using std::cerr;
160 using std::cout;
161
162 using namespace simgear::pkg;
163
164 extern osg::ref_ptr<osgViewer::Viewer> viewer;
165
166 // Return the current base package version
167 string fgBasePackageVersion(const SGPath& base_path) {
168 SGPath p(base_path);
169 p.append("version");
170 if (!p.exists()) {
171 return string();
172 }
173
174 sg_gzifstream in( p );
175 if (!in.is_open()) {
176 return string();
177 }
178
179 string version;
180 in >> version;
181
182 return version;
183 }
184
185 std::optional<FGBasePackageInfo> fgBasePackageInfo(const SGPath& path)
186 {
187 SGPath p = path / "base_package.json";
188 if (!p.exists()) {
189 return {};
190 }
191
192 sg_ifstream in(p);
193 if (!in.is_open()) {
194 return {};
195 }
196
197 const auto content = in.read_all();
198 cJSON* json = cJSON_Parse(content.c_str());
199
200 FGBasePackageInfo r;
201
202 auto ver = cJSON_GetObjectItem(json, "version");
203 if (ver) {
204 r.version = ver->valuestring;
205 }
206
207 auto suf = cJSON_GetObjectItem(json, "fgdata-suffix");
208 if (suf) {
209 r.suffix = suf->valuestring;
210 }
211
212 r.buildDate = cJSON_GetObjectItem(json, "build-date")->valuestring;
213 r.gitRevision = cJSON_GetObjectItem(json, "fgdata-sha")->valuestring;
214
215 cJSON_Delete(json);
216 return r;
217 }
218
219 class FindAndCacheAircraft : public AircraftDirVistorBase
220 {
221 public:
222 FindAndCacheAircraft(SGPropertyNode* autoSave)
223 {
224 _cache = autoSave->getNode("sim/startup/path-cache", true);
225 }
226
227 void setDidUseLauncher(bool didUseLauncher)
228 {
229 _didUseLauncher = didUseLauncher;
230 }
231
232 /**
233 * @brief haveExplicitAircraft - check if the combination of /sim/aircraft
234 * and /sim/aircraft-dir defines an explicit -set.xml. We need to detect
235 * this case to short-circuit package detection
236 * @return
237 */
238 bool haveExplicitAircraft() const
239 {
240 const std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
241 if (aircraftDir.empty()) {
242 return false;
243 }
244
245 const std::string aircraft = fgGetString( "/sim/aircraft", "");
246 SGPath setFile = SGPath::fromUtf8(aircraftDir) / (aircraft + "-set.xml");
247 return setFile.exists();
248 }
249
250 bool loadAircraft()
251 {
252 std::string aircraft = fgGetString( "/sim/aircraft", "");
253 if (aircraft.empty()) {
254 flightgear::fatalMessageBoxWithoutExit("No aircraft",
255 "No aircraft was specified");
256 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
257 return false;
258 }
259
260 _searchAircraft = aircraft + "-set.xml";
261 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
262 if (!aircraftDir.empty()) {
263 // aircraft-dir was set, skip any searching at all, if it's valid
264 simgear::Dir acPath(aircraftDir);
265 SGPath setFile = acPath.file(_searchAircraft);
266 if (setFile.exists()) {
267 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
268
269 try {
270 readProperties(setFile, globals->get_props());
271 } catch ( const sg_exception &e ) {
272 SG_LOG(SG_IO, SG_ALERT,
273 "Error reading aircraft: " << e.getFormattedMessage());
274 flightgear::addSentryBreadcrumb("Aircraft-dir=" + aircraftDir, "error");
275 SG_LOG(SG_IO, SG_ALERT, "aircraft dir is:" << aircraftDir);
276 flightgear::fatalMessageBoxWithoutExit(
277 "Error reading aircraft",
278 "An error occured reading the requested aircraft (" + aircraft + ")",
279 e.getFormattedMessage());
280 return false;
281 }
282
283 checkAircraftMinVersion();
284 checkAircraftDirName();
285
286 // apply state after the -set.xml, but before any options are are set
287 flightgear::applyInitialState();
288 return true;
289 } else {
290 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
291 "' not found in specified dir:" << aircraftDir);
292 flightgear::addSentryBreadcrumb("Aircraft-dir=" + aircraftDir, "error");
293 flightgear::fatalMessageBoxWithoutExit(
294 "Aircraft not found",
295 "The requested aircraft (" + aircraft + ") could not be found "
296 "in the specified location. (" +
297 aircraftDir + ")",
298 aircraftDir);
299 return false;
300 }
301 }
302
303 if (!checkCache()) {
304 flightgear::addSentryBreadcrumb("Scanning aircraft paths", "info");
305
306 // prepare cache for re-scan
307 SGPropertyNode* n = _cache->getNode("fg-root", true);
308 n->setStringValue(globals->get_fg_root().utf8Str());
309 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
310 n = _cache->getNode("fg-aircraft", true);
311 n->setStringValue(getAircraftPaths().c_str());
312 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
313 _cache->removeChildren("aircraft");
314
315 visitAircraftPaths();
316 }
317
318 if (_foundPath.isNull()) {
319 SG_LOG(SG_GENERAL, SG_ALERT,
320 "Cannot find the specified aircraft: '" << aircraft << "'");
321
322 flightgear::addSentryBreadcrumb("Aircraft paths: " + SGPath::join(globals->get_aircraft_paths(), ";"), "error");
323
324 SG_LOG(SG_GENERAL, SG_ALERT, "\tin paths:" << SGPath::join(globals->get_aircraft_paths(), ";"));
325
326 std::string notFoundMessage;
327 // don't report failures where the launcher was not used, to Sentry,
328 // since they are nearly all configuration problems.
329 bool reportToSentry = _didUseLauncher;
330
331 if (globals->get_aircraft_paths().empty()) {
332 notFoundMessage = "The requested aircraft (" + aircraft + ") could not be found. No aircraft paths are configured.";
333 reportToSentry = false; // no need to log these
334 } else {
335 notFoundMessage = "The requested aircraft (" + aircraft + ") could not be found in any of the search paths.";
336 }
337
338 flightgear::fatalMessageBoxWithoutExit(
339 "Aircraft not found",
340 notFoundMessage,
341 {},
342 reportToSentry);
343 return false;
344 }
345
346 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath);
347 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
348 if (!_foundPath.exists()) {
349 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath);
350 return false;
351 }
352
353
354 try {
355 readProperties(_foundPath, globals->get_props());
356 } catch ( const sg_exception &e ) {
357 SG_LOG(SG_INPUT, SG_ALERT,
358 "Error reading aircraft: " << e.getFormattedMessage());
359 flightgear::fatalMessageBoxWithoutExit(
360 "Error reading aircraft",
361 "An error occured reading the requested aircraft (" + aircraft + ")",
362 e.getFormattedMessage());
363 return false;
364 }
365
366 // apply state after the -set.xml, but before any options are are set
367 flightgear::applyInitialState();
368
369 checkAircraftMinVersion();
370 checkAircraftDirName();
371
372 return true;
373 }
374
375 private:
376 std::string getAircraftPaths()
377 {
378 return SGPath::join(globals->get_aircraft_paths(), ";");
379 }
380
381 bool checkCache()
382 {
383 if (globals->get_fg_root().utf8Str() != _cache->getStringValue("fg-root", "")) {
384 return false; // cache mismatch
385 }
386
387 if (getAircraftPaths() != _cache->getStringValue("fg-aircraft", "")) {
388 return false; // cache mismatch
389 }
390
391 std::vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
392 for (unsigned int i = 0; i < cache.size(); i++) {
393 const std::string name = cache[i]->getStringValue("file", "");
394 if (!simgear::strutils::iequals(_searchAircraft, name)) {
395 continue;
396 }
397
398 SGPath xml(cache[i]->getStringValue("path", ""));
399 xml.append(name);
400 if (xml.exists()) {
401 flightgear::addSentryBreadcrumb("Found aircraft via cache", "info");
402 _foundPath = xml;
403 return true;
404 }
405
406 return false;
407 } // of aircraft in cache iteration
408
409 return false;
410 }
411
412 virtual VisitResult visit(const SGPath& p)
413 {
414 SGPath realPath = p.realpath();
415 // create cache node
416 int i = 0;
417 while (1) {
418 if (!_cache->getChild("aircraft", i++, false))
419 break;
420 }
421
422 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
423
424 std::string fileName(realPath.file());
425 n = entry->getNode("file", true);
426 n->setStringValue(fileName);
427 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
428
429 n = entry->getNode("path", true);
430 n->setStringValue(realPath.dir());
431 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
432
433 if (simgear::strutils::iequals(fileName, _searchAircraft)) {
434 _foundPath = realPath;
435 return VISIT_DONE;
436 }
437
438 return VISIT_CONTINUE;
439 }
440
441 bool checkAircraftMinVersion()
442 {
443 SGPropertyNode* minVersionNode = globals->get_props()->getNode("/sim/minimum-fg-version");
444 if (minVersionNode) {
445 std::string minVersion = minVersionNode->getStringValue();
446 const int c = simgear::strutils::compare_versions(FLIGHTGEAR_VERSION, minVersion, 2);
447 if (c < 0) {
448 SG_LOG(SG_AIRCRAFT, SG_DEV_ALERT, "Aircraft minimum version (" << minVersion <<
449 ") is higher than FG version:" << FLIGHTGEAR_VERSION);
450 flightgear::modalMessageBox("Aircraft requires newer version of FlightGear",
451 "The selected aircraft requires FlightGear version " + minVersion
452 + " to work correctly. Some features may not work as expected, or the aircraft may not load at all.");
453 return false;
454 }
455 } else {
456 SG_LOG(SG_AIRCRAFT, SG_DEV_ALERT, "Aircraft does not specify a minimum FG version: please add one at /sim/minimum-fg-version");
457 }
458
459 auto compatNodes = globals->get_props()->getNode("/sim")->getChildren("compatible-fg-version");
460 if (!compatNodes.empty()) {
461 bool showCompatWarning = true;
462
463 // if we have at least one compatibility node, then it needs to match
464 for (const auto& cn : compatNodes) {
465 const auto v = cn->getStringValue();
466 if (simgear::strutils::compareVersionToWildcard(FLIGHTGEAR_VERSION, v)) {
467 showCompatWarning = false;
468 break;
469 }
470 }
471
472 if (showCompatWarning) {
473 flightgear::modalMessageBox("Aircraft not compatible with this version",
474 "The selected aircraft has not been checked for compatability with this version of FlightGear (" FLIGHTGEAR_VERSION "). "
475 "Some aircraft features might not work, or might be displayed incorrectly.");
476 }
477 }
478
479 return true;
480 }
481
482 bool checkAircraftDirName()
483 {
484 auto expectedDirNode = globals->get_props()->getNode("/sim/expected-aircraft-dir-name");
485 const string aircraftId = fgGetString("/sim/aircraft");
486 if (aircraftId != fgGetString("/sim/aircraft-id")){
487 // Skip the check for aircraft installed from catalog.
488 return true;
489 }
490
491 if (expectedDirNode) {
492 const string expectedDir = expectedDirNode->getStringValue();
493 const SGPath dir(fgGetString("/sim/aircraft-dir"));
494 if (dir.file() != expectedDirNode->getStringValue()) {
495 flightgear::fatalMessageBoxThenExit("Aircraft folder named incorrectly",
496 "The folder of the selected aircraft must be named '" + expectedDir +
497 "' (instead of '" + dir.file() + "') to work correctly. If you downloaded it yourself, " +
498 "please ensure the folder is called '" +
499 expectedDir + "' and re-name if necessary.",
500 {}, EXIT_FAILURE, false /* don't report to Sentry */);
501 return false;
502 }
503 } else {
504 // TODO Uncomment for the next release.
505 //SG_LOG(SG_AIRCRAFT, SG_DEV_ALERT, "Aircraft does not specify the required aircraft directory name: please add one at /sim/expected-aircraft-dir-name");
506 }
507 return true;
508 }
509
510 std::string _searchAircraft;
511 SGPath _foundPath;
512 SGPropertyNode* _cache = nullptr;
513 bool _didUseLauncher = false;
514 };
515
516 #ifdef _WIN32
517 static SGPath platformDefaultDataPath()
518 {
519 SGPath appDataPath = SGPath::fromEnv("APPDATA");
520
521 if (appDataPath.isNull()) {
522 flightgear::fatalMessageBoxThenExit(
523 "FlightGear", "Unable to get the value of APPDATA.",
524 "FlightGear is unable to retrieve the value of the APPDATA environment "
525 "variable. This is quite unexpected on Windows platforms, and FlightGear "
526 "can't continue its execution without this value, sorry.");
527 }
528
529 return appDataPath / "flightgear.org";
530 }
531
532 #elif defined(SG_MAC)
533
534 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
535
536 #else
537 static SGPath platformDefaultDataPath()
538 {
539 return SGPath::home() / ".fgfs";
540 }
541 #endif
542
543 #if defined(SG_WINDOWS)
544 static HANDLE static_fgHomeWriteMutex = nullptr;
545 #endif
546
547 ///////////////////////////////////////////////////////////////////////////////
548
549 static simgear::LogCallback* static_logToHomeCallback = nullptr;
550
551 static void rotateOldLogFiles()
552 {
553 const int maxLogCount = 10;
554 const auto homePath = globals->get_fg_home();
555
556 for (int i = maxLogCount; i > 0; --i) {
557 const auto name = "fgfs_" + std::to_string(i - 1) + ".log";
558 SGPath curLogFile = homePath / name;
559 if (curLogFile.exists()) {
560 auto newName = "fgfs_" + std::to_string(i) + ".log";
561 curLogFile.rename(homePath / newName);
562 }
563 }
564
565 SGPath p = homePath / "fgfs.log";
566 if (!p.exists())
567 return;
568 SGPath log0Path = homePath / "fgfs_0.log";
569 if (!p.rename(log0Path)) {
570 std::cerr << "Failed to rename " << p.str() << " to " << log0Path.str() << std::endl;
571 }
572 }
573
574 static void closeHomeDirLogFile()
575 {
576 if (static_logToHomeCallback) {
577 sglog().removeCallback(static_logToHomeCallback);
578 delete static_logToHomeCallback;
579 static_logToHomeCallback = nullptr;
580 }
581 }
582
583 void fgInitLogging(const std::string& pri)
584 {
585 const bool readOnlyFGHome = fgGetBool("/sim/fghome-readonly");
586 if (readOnlyFGHome) {
587 return;
588 }
589
590 sgDebugPriority fileLogLevel = SG_INFO;
591 // https://sourceforge.net/p/flightgear/codetickets/2100/
592 if (!pri.empty()) {
593 try {
594 fileLogLevel = std::min(fileLogLevel, logstream::priorityFromString(pri));
595 } catch (std::exception& ) {
596 // let's not worry about this, and just log at INFO
597 }
598 }
599
600 SGPath logPath = globals->get_fg_home() / "fgfs.log";
601 if (logPath.exists()) {
602 rotateOldLogFiles();
603 }
604
605 static_logToHomeCallback = sglog().logToFile(logPath, SG_ALL, fileLogLevel);
606 }
607
608 ///////////////////////////////////////////////////////////////////////////////
609 SGPath fgHomePath()
610 {
611 return SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
612 }
613
614 InitHomeResult fgInitHome(int argc, char** argv)
615 {
616 SGPath dataPath = fgHomePath();
617 globals->set_fg_home(dataPath);
618
619 simgear::Dir fgHome(dataPath);
620 if (!fgHome.exists()) {
621 fgHome.create(0755);
622 }
623
624 if (!fgHome.exists()) {
625 flightgear::fatalMessageBoxWithoutExit(
626 "Problem setting up user data",
627 "Unable to create the user-data storage folder at '" +
628 dataPath.utf8Str() + "'.");
629 return InitHomeAbort;
630 }
631
632 const auto explicitReadOnly = flightgear::Options::checkForArgEnable(argc, argv, "read-only");
633 if (explicitReadOnly) {
634 // user / config forced us into readonly mode, fine
635 SG_LOG(SG_GENERAL, SG_MANDATORY_INFO, "Running with FG_HOME readonly");
636 fgSetBool("/sim/fghome-readonly", true);
637 return InitHomeExplicitReadOnly;
638 }
639
640 // todo: move this code into MultipleInstanceLock.cxx
641 InitHomeResult result = InitHomeOkay;
642 #if defined(SG_WINDOWS)
643 // don't use a PID file on Windows, because deleting on close is
644 // unreliable and causes false-positives. Instead, use a named
645 // mutex.
646
647 static_fgHomeWriteMutex = CreateMutexA(nullptr, FALSE, "org.flightgear.fgfs.primary");
648 if (static_fgHomeWriteMutex == nullptr) {
649 printf("CreateMutex error: %d\n", GetLastError());
650 SG_LOG(SG_GENERAL, SG_ALERT, "Failed to create mutex for multi-app protection");
651 return InitHomeAbort;
652 } else if (GetLastError() == ERROR_ALREADY_EXISTS) {
653 SG_LOG(SG_GENERAL, SG_MANDATORY_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
654 fgSetBool("/sim/fghome-readonly", true);
655 return InitHomeReadOnly;
656 } else {
657 SG_LOG(SG_GENERAL, SG_INFO, "Created multi-app mutex, we are in writeable mode");
658 result = InitHomeOkay;
659 }
660 #else
661 // write our PID, and check writeability
662 SGPath pidPath(dataPath, "fgfs_lock.pid");
663 std::string ps = pidPath.utf8Str();
664
665 if (pidPath.exists()) {
666 int fd = ::open(ps.c_str(), O_RDONLY, 0644);
667 if (fd < 0) {
668 SG_LOG(SG_GENERAL, SG_ALERT, "failed to open local file:" << pidPath
669 << "\n\tdue to:" << simgear::strutils::error_string(errno));
670 return InitHomeAbort;
671 }
672
673 int err = ::flock(fd, LOCK_EX | LOCK_NB);
674 if (err < 0) {
675 if ( errno == EWOULDBLOCK) {
676 SG_LOG(SG_GENERAL, SG_ALERT, "flightgear instance already running, switching to FG_HOME read-only. ");
677 SG_LOG(SG_GENERAL, SG_ALERT, "Couldn't flock() file at:" << pidPath);
678
679 // set a marker property so terrasync/navcache don't try to write
680 // from secondary instances
681 fgSetBool("/sim/fghome-readonly", true);
682 return InitHomeReadOnly;
683 } else {
684 SG_LOG(SG_GENERAL, SG_ALERT, "failed to lock file:" << pidPath
685 << "\n\tdue to:" << simgear::strutils::error_string(errno));
686 return InitHomeAbort;
687 }
688 }
689
690 // we locked it!
691 result = InitHomeOkay;
692 } else {
693 char buf[16];
694 std::string ps = pidPath.utf8Str();
695
696 ssize_t len = snprintf(buf, 16, "%d\n", getpid());
697 int fd = ::open(ps.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
698 if (fd < 0) {
699 SG_LOG(SG_GENERAL, SG_ALERT, "failed to open local file:" << pidPath
700 << "\n\tdue to:" << simgear::strutils::error_string(errno));
701 return InitHomeAbort;
702 }
703
704 int err = write(fd, buf, len);
705 if (err < 0) {
706 SG_LOG(SG_GENERAL, SG_ALERT, "failed to write to lock file:" << pidPath
707 << "\n\tdue to:" << simgear::strutils::error_string(errno));
708 return InitHomeAbort;
709 }
710
711 err = flock(fd, LOCK_EX);
712 if (err != 0) {
713 SG_LOG(SG_GENERAL, SG_ALERT, "failed to lock file:" << pidPath
714 << "\n\tdue to:" << simgear::strutils::error_string(errno));
715 return InitHomeAbort;
716 }
717
718 result = InitHomeOkay;
719 }
720 #endif
721 // now we know we're the main copy, take an exclusive lock until we know FGData / nav-cache are correct
722 // this will cause either the launcher init or the splash screen to block in read-only copies, until
723 // we release the exclusive lock after nav-cache build is done.
724 flightgear::ExclusiveInstanceLock::createInstance("init-home");
725
726 fgSetBool("/sim/fghome-readonly", false);
727 return result;
728 }
729
730 void fgShutdownHome()
731 {
732 #if defined(SG_WINDOWS)
733 if (static_fgHomeWriteMutex) {
734 CloseHandle(static_fgHomeWriteMutex);
735 }
736 #else
737 if (fgGetBool("/sim/fghome-readonly") == false) {
738 SGPath pidPath = globals->get_fg_home() / "fgfs_lock.pid";
739 pidPath.remove();
740 }
741 #endif
742 closeHomeDirLogFile();
743 }
744
745 void fgDeleteLockFile()
746 {
747 #if defined(SG_WINDOWS)
748 // there's no file here, so we can't actually delete anything
749 #else
750 SGPath pidPath = globals->get_fg_home() / "fgfs_lock.pid";
751 pidPath.remove();
752 #endif
753 }
754
755 static void createBaseStorageDirForAddons(const SGPath& exportDir)
756 {
757 SGPath addonStorageBasePath = exportDir / "Addons";
758 if (addonStorageBasePath.exists()) {
759 if (!addonStorageBasePath.isDir()) {
760 throw sg_error(
761 "Unable to create add-on storage base directory, because the entry "
762 "already exists but is not a directory: '" +
763 addonStorageBasePath.utf8Str() + "'");
764 }
765 } else {
766 simgear::Dir(addonStorageBasePath).create(0777); // respect user's umask
767 }
768 }
769
770 struct SimLogFileLine : SGPropertyChangeListener
771 {
772 SimLogFileLine() {
773 fgAddChangeListener(this, "/sim/log-file-line");
774 }
775 virtual void valueChanged(SGPropertyNode* node) {
776 bool fileLine = node->getBoolValue();
777 sglog().setFileLine(fileLine);
778 }
779 };
780
781 // Read in configuration (file and command line)
782 int fgInitConfig ( int argc, char **argv, bool reinit )
783 {
784 SGPath dataPath = globals->get_fg_home();
785
786 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
787 if (!exportDir.exists()) {
788 exportDir.create(0755);
789 }
790
791 // Reserve a directory where add-ons can write. There will be a subdir for
792 // each add-on, see Addon::createStorageDir() and Addon::getStoragePath().
793 createBaseStorageDirForAddons(exportDir.path());
794
795 // Set /sim/fg-home. Use FG_HOME if necessary.
796 // deliberately not a tied property, for SGPath::validate() security
797 // write-protect to avoid accidents
798 SGPropertyNode *home = fgGetNode("/sim", true);
799 home->removeChild("fg-home", 0);
800 home = home->getChild("fg-home", 0, true);
801 home->setStringValue(dataPath.utf8Str());
802 home->setAttribute(SGPropertyNode::WRITE, false);
803
804 fgSetDefaults();
805 flightgear::Options* options = flightgear::Options::sharedInstance();
806 if (!reinit) {
807 auto result = options->init(argc, argv, dataPath);
808 if (result != flightgear::FG_OPTIONS_OK) {
809 return result;
810 }
811 }
812
813 // establish default for developer-mode based upon compiled build types
814 bool developerMode = true;
815 if (!strcmp(FG_BUILD_TYPE, "Release")) {
816 developerMode = false;
817 }
818
819 // allow command line to override
820 const simgear::optional<bool> devOption = options->checkBoolOptionSet("developer");
821 if (devOption.has_value()) { // User specified the developer option
822 developerMode = devOption.value();
823 }
824
825 auto node = fgGetNode("/sim/developer-mode", true);
826 // ensure this value survives reset
827 node->setAttribute(SGPropertyNode::PRESERVE, true);
828 node->setBoolValue(developerMode);
829 sglog().setDeveloperMode(developerMode);
830
831 static SimLogFileLine simLogFileLine;
832
833 // Read global defaults from $FG_ROOT/defaults
834 SG_LOG(SG_GENERAL, SG_DEBUG, "Reading global defaults");
835 SGPath defaultsXML = globals->get_fg_root() / "defaults.xml";
836 if (!defaultsXML.exists()) {
837 flightgear::fatalMessageBoxThenExit(
838 "Missing file",
839 "Couldn't load an essential simulator data file.",
840 defaultsXML.utf8Str());
841 }
842
843 if(!fgLoadProps("defaults.xml", globals->get_props()))
844 {
845 flightgear::fatalMessageBoxThenExit(
846 "Corrupted file",
847 "Couldn't load an essential simulator data file as it is corrupted.",
848 defaultsXML.utf8Str());
849 }
850 SG_LOG(SG_GENERAL, SG_DEBUG, "Finished Reading global defaults");
851
852 // do not load user settings when reset to default is requested, or if
853 // told to explicitly ignore
854 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
855 {
856 SG_LOG(SG_GENERAL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
857 } else {
858 globals->loadUserSettings(dataPath);
859 }
860
861 return flightgear::FG_OPTIONS_OK;
862 }
863
864 static void initAircraftDirsNasalSecurity()
865 {
866 // deliberately not a tied property, for SGPath::validate() security
867 // write-protect to avoid accidents
868 SGPropertyNode* sim = fgGetNode("/sim", true);
869 sim->removeChildren("fg-aircraft");
870
871 int index = 0;
872 const PathList& aircraft_paths = globals->get_aircraft_paths();
873 for (PathList::const_iterator it = aircraft_paths.begin();
874 it != aircraft_paths.end(); ++it, ++index )
875 {
876 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
877 n->setStringValue(it->utf8Str());
878 n->setAttribute(SGPropertyNode::WRITE, false);
879 }
880 }
881
882 void fgInitAircraftPaths(bool reinit)
883 {
884 if (!globals->packageRoot()) {
885 fgInitPackageRoot();
886 }
887
888 SGSharedPtr<Root> pkgRoot(globals->packageRoot());
889 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
890 aircraftProp->setAttribute(SGPropertyNode::PRESERVE, true);
891
892 if (!reinit) {
893 flightgear::Options::sharedInstance()->initPaths();
894 }
895 }
896
897 int fgInitAircraft(bool reinit, bool didUseLauncher)
898 {
899 if (!reinit) {
900 auto r = flightgear::Options::sharedInstance()->initAircraft();
901 if (r == flightgear::FG_OPTIONS_SHOW_AIRCRAFT)
902 return r;
903 }
904
905 FindAndCacheAircraft f(globals->get_props());
906 f.setDidUseLauncher(didUseLauncher);
907 const bool haveExplicit = f.haveExplicitAircraft();
908
909 SGSharedPtr<Root> pkgRoot(globals->packageRoot());
910 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
911 SGPropertyNode* aircraftDirProp = fgGetNode("/sim/aircraft-dir", true);
912
913 // ensure aircraft-dir survives reset, so we find the same aircraft
914 // after a reset as we did prior to it. Without this, aircraft
915 // can unintentionally change on a reset
916 aircraftDirProp->setAttribute(SGPropertyNode::PRESERVE, true);
917
918 const string fullyQualifiedAircraftId = fgGetString("/sim/aircraft-id");
919 string aircraftId = fullyQualifiedAircraftId.empty() ? aircraftProp->getStringValue() : fullyQualifiedAircraftId;
920
921 flightgear::addSentryTag("aircraft", aircraftId);
922
923 const auto acdp = SGPath::fromUtf8(aircraftDirProp->getStringValue());
924 flightgear::addSentryTag("aircraft-dir", acdp.file());
925
926 PackageRef acftPackage;
927 if (!haveExplicit) {
928 acftPackage = pkgRoot->getPackageById(aircraftId);
929 }
930
931 if (acftPackage) {
932 if (acftPackage->isInstalled()) {
933 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft from package:" << acftPackage->qualifiedId());
934 // if we resolved a non-qualified ID, set the full one back to /sim/aircraft-id
935 fgSetString("/sim/aircraft-id", acftPackage->qualifiedId());
936
937 // replace this tag, so we know which hangar is in use
938 flightgear::addSentryTag("aircraft", acftPackage->qualifiedId());
939
940 // set catalog path so intra-package dependencies within the catalog
941 // are resolved correctly.
942 globals->set_catalog_aircraft_path(acftPackage->catalog()->installRoot());
943
944 // set aircraft-dir to short circuit the search process
945 InstallRef acftInstall = acftPackage->install();
946 fgSetString("/sim/aircraft-dir", acftInstall->path().utf8Str());
947
948 // overwrite the fully qualified ID with the aircraft one, so the
949 // code in FindAndCacheAircraft works as normal
950 // note since we may be using a variant, we can't use the package ID
951 size_t lastDot = aircraftId.rfind('.');
952 if (lastDot != std::string::npos) {
953 aircraftId = aircraftId.substr(lastDot + 1);
954 }
955 aircraftProp->setStringValue(aircraftId);
956 fgSetBool("/sim/aircraft-from-package", true);
957
958 // run the traditional-code path below
959 } else {
960 #if 0
961 // naturally the better option would be to on-demand install it!
962 flightgear::fatalMessageBoxWithoutExit(
963 "Aircraft not installed",
964 "Requested aircraft is not currently installed.",
965 aircraftId);
966
967 return flightgear::FG_OPTIONS_ERROR;
968 #endif
969 // fall back the default aircraft instead
970 }
971 }
972
973 initAircraftDirsNasalSecurity();
974
975 if (!f.loadAircraft()) {
976 return flightgear::FG_OPTIONS_ERROR;
977 }
978
979 return flightgear::FG_OPTIONS_OK;
980 }
981
982 /**
983 * Initialize vor/ndb/ils/fix list management and query systems (as
984 * well as simple airport db list)
985 * This is called multiple times in the case of a cache rebuild,
986 * to allow lengthy caching to take place in the background, without
987 * blocking the main/UI thread.
988 */
989 bool
990 fgInitNav ()
991 {
992 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
993 static bool doingRebuild = false;
994
995 if (!cache) {
996 cache = flightgear::NavDataCache::createInstance();
997 doingRebuild = cache->isRebuildRequired();
998 }
999
1000 static const char* splashIdentsByRebuildPhase[] = {
1001 "loading-nav-dat",
1002 "navdata-reading-apt-dat-files",
1003 "navdata-loading-airports",
1004 "navdata-navaids",
1005 "navdata-fixes",
1006 "navdata-pois"
1007 };
1008
1009 if (doingRebuild) {
1010 flightgear::NavDataCache::RebuildPhase phase;
1011 phase = cache->rebuild();
1012 if (phase != flightgear::NavDataCache::REBUILD_DONE) {
1013 // update the splash text based on percentage, phase
1014
1015 fgSplashProgress(splashIdentsByRebuildPhase[phase],
1016 cache->rebuildPhaseCompletionPercentage());
1017
1018 // sleep to give the rebuild thread more time
1019 SGTimeStamp::sleepForMSec(50);
1020 return false;
1021 }
1022 }
1023
1024 FGTACANList *channellist = new FGTACANList;
1025 globals->set_channellist( channellist );
1026
1027 SGPath path(globals->get_fg_root());
1028 path.append( "Navaids/TACAN_freq.dat" );
1029 flightgear::NavLoader().loadTacan(path, channellist);
1030
1031 return true;
1032 }
1033
1034 // General house keeping initializations
1035 bool fgInitGeneral() {
1036
1037 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1038 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1039
1040 if ( globals->get_fg_root().isNull() ) {
1041 // No root path set? Then bail ...
1042 SG_LOG( SG_GENERAL, SG_ALERT,
1043 "Cannot continue without a path to the base package "
1044 << "being defined." );
1045 return false;
1046 }
1047 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << globals->get_fg_root() << '"' << endl );
1048
1049 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
1050 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
1051 fgSetString("/sim/startup/browser-app", globals->get_browser());
1052
1053 simgear::Dir cwd(simgear::Dir::current());
1054 SGPropertyNode *curr = fgGetNode("/sim", true);
1055 curr->removeChild("fg-current", 0);
1056 curr = curr->getChild("fg-current", 0, true);
1057 curr->setStringValue(cwd.path().utf8Str());
1058 curr->setAttribute(SGPropertyNode::WRITE, false);
1059
1060 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1061 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1062
1063 sgUserDataInit( globals->get_props() );
1064 flightgear::addSentryTag("have-reset", "no");
1065
1066 return true;
1067 }
1068
1069 // Write various configuraton values out to the logs
1070 void fgOutputSettings()
1071 {
1072 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
1073 SG_LOG( SG_GENERAL, SG_INFO, "============= =====" );
1074
1075 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
1076 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
1077 SG_LOG( SG_GENERAL, SG_INFO, "download-dir = " << '"' << fgGetString("/sim/paths/download-dir") << '"' );
1078 SG_LOG( SG_GENERAL, SG_INFO, "terrasync-dir = " << '"' << fgGetString("/sim/terrasync/scenery-dir") << '"' );
1079
1080 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << SGPath::join(globals->get_aircraft_paths(), "\n\t") );
1081 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << SGPath::join(globals->get_fg_scenery(), "\n\t") );
1082 }
1083
1084 // This is the top level init routine which calls all the other
1085 // initialization routines. If you are adding a subsystem to flight
1086 // gear, its initialization call should located in this routine.
1087 // Returns non-zero if a problem encountered.
1088 void fgCreateSubsystems(bool duringReset) {
1089
1090 SG_LOG( SG_GENERAL, SG_INFO, "== Creating Subsystems");
1091
1092 // Fetch the subsystem manager.
1093 auto mgr = globals->get_subsystem_mgr();
1094
1095 globals->get_event_mgr()->init();
1096 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1097
1098 // SGSubsystemMgr::INIT
1099 {
1100 // Initialize the property interpolator subsystem. Put into the INIT
1101 // group because the "nasal" subsystem may need it at GENERAL take-down.
1102 mgr->add<FGInterpolator>();
1103 mgr->add<Highlight>();
1104 mgr->add<NewGUI>();
1105 }
1106
1107 // SGSubsystemMgr::GENERAL
1108 {
1109 mgr->add<FGProperties>();
1110 mgr->add<flightgear::AirportDynamicsManager>();
1111 mgr->add("performance-mon",
1112 new SGPerformanceMonitor(
1113 mgr,
1114 fgGetNode("/sim/performance-monitor", true)
1115 )
1116 );
1117
1118 // Initialize the material property subsystem.
1119 SGPath mpath( globals->get_fg_root() );
1120 mpath.append( fgGetString("/sim/rendering/materials-file") );
1121 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath, globals->get_props()) ) {
1122 throw sg_io_exception("Error loading materials file", mpath);
1123 }
1124
1125 // may exist already due to GUI startup or --load-tape=http...
1126 if (!mgr->get_subsystem<FGHTTPClient>()) {
1127 mgr->add<FGHTTPClient>();
1128 }
1129 mgr->add<FGDNSClient>();
1130
1131 // Initialize the weather modeling subsystem
1132 mgr->add<FGEnvironmentMgr>();
1133 mgr->add<Ephemeris>();
1134 mgr->add("xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"));
1135
1136 mgr->add<FGRouteMgr>();
1137 mgr->add<FGIO>();
1138 mgr->add<FGLogger>();
1139
1140 mgr->add<FGControls>();
1141 mgr->add<FGInput>();
1142 mgr->add<FGFlightHistory>();
1143
1144 {
1145 SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
1146 if( NULL != httpd )
1147 mgr->add("httpd", httpd);
1148 }
1149
1150 if (!duringReset) {
1151 mgr->add<FGTide>();
1152 }
1153 }
1154
1155 // SGSubsystemMgr::FDM
1156 {
1157 mgr->add<FDMShell>();
1158
1159 // Initialize the aircraft systems and instrumentation (before the
1160 // autopilot.)
1161 mgr->add<FGSystemMgr>();
1162 mgr->add<FGInstrumentMgr>();
1163 mgr->add("xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM);
1164 }
1165
1166 // SGSubsystemMgr::POST_FDM
1167 {
1168 mgr->add<PerformanceDB>();
1169 mgr->add<FGATCManager>();
1170 mgr->add<FGAIManager>();
1171 mgr->add<FGMultiplayMgr>();
1172
1173 #ifdef ENABLE_SWIFT
1174 mgr->add<flightgear::swift::SwiftConnection>();
1175 #endif
1176
1177 // FGReplay.
1178 //
1179 // FGReplay is after FGMultiplayMgr, so that it can record the most
1180 // recent MP packets.
1181 //
1182 // FGReplay is before FGAIManager so that, when replaying, it can push
1183 // MP packets into FGMultiplayMgr's queue before FGAIManager reads from
1184 // this queue.
1185 //
1186 // We also call FGReplay::init() method here, to work around a
1187 // problem where JSBSim appears to rely on FGReplay creating certain
1188 // properties before it is initialised. This caused problems when
1189 // FGReplay was changed to be POST_FDM.
1190 mgr->add<FGReplay>();
1191 mgr->get_subsystem<FGReplay>()->init(); // Special case.
1192
1193 //mgr->add<FGAIManager>();
1194 mgr->add<FGSubmodelMgr>();
1195
1196 // It's probably a good idea to initialize the top level traffic manager
1197 // After the AI and ATC systems have been initialized properly.
1198 // AI Traffic manager
1199 mgr->add<FGTrafficManager>();
1200
1201 fgSetArchivable("/sim/panel/visibility");
1202 fgSetArchivable("/sim/panel/x-offset");
1203 fgSetArchivable("/sim/panel/y-offset");
1204 fgSetArchivable("/sim/panel/jitter");
1205 }
1206
1207 // SGSubsystemMgr::DISPLAY
1208 {
1209 #ifdef ENABLE_HUD
1210 mgr->add<HUD>();
1211 #endif
1212 mgr->add<flightgear::CockpitDisplayManager>();
1213
1214 simgear::canvas::Canvas::setSystemAdapter(
1215 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
1216 );
1217 mgr->add<CanvasMgr>();
1218
1219 auto canvasGui = new GUIMgr;
1220 mgr->add("CanvasGUI", canvasGui, SGSubsystemMgr::DISPLAY);
1221 auto guiCamera = flightgear::getGUICamera(flightgear::CameraGroup::getDefault());
1222 canvasGui->setGUIViewAndCamera(globals->get_renderer()->getView(), guiCamera);
1223
1224 #ifdef ENABLE_AUDIO_SUPPORT
1225 mgr->add<FGVoiceMgr>();
1226 #endif
1227
1228 // ordering here is important : Nasal (via events), then models, then views
1229 if (!duringReset) {
1230 mgr->add<FGLight>();
1231 mgr->add("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1232 }
1233
1234 mgr->add<FGAircraftModel>();
1235 mgr->add<FGModelMgr>();
1236 mgr->add<FGViewMgr>();
1237 }
1238
1239 // SGSubsystemMgr::SOUND
1240 {
1241 // Sound manager uses an own subsystem group "SOUND" which is the last
1242 // to be updated in every loop.
1243 // Sound manager is updated last so it can use the CPU while the GPU
1244 // is processing the scenery (doubled the frame-rate for me) -EMH-
1245 mgr->add<FGSoundManager>();
1246
1247 #ifdef ENABLE_IAX
1248 // Initialize the FGCom subsystem.
1249 // very important this goes in the SOUND group, since IAXClient
1250 // depends on OpenAL, which is shutdown when the SOUND group
1251 // shutdown.
1252 // Sentry: FLIGHTGEAR-66
1253 mgr->add<FGCom>();
1254 #endif
1255 }
1256 }
1257
1258 void fgPostInitSubsystems()
1259 {
1260 SGTimeStamp st;
1261 st.stamp();
1262
1263 // Fetch the subsystem manager.
1264 auto mgr = globals->get_subsystem_mgr();
1265
1266 ////////////////////////////////////////////////////////////////////////
1267 // Initialize the Nasal interpreter.
1268 // Do this last, so that the loaded scripts see initialized state
1269 ////////////////////////////////////////////////////////////////////////
1270 mgr->add<FGNasalSys>();
1271
1272 // initialize methods that depend on other subsystems.
1273 st.stamp();
1274 mgr->postinit();
1275 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
1276
1277 ////////////////////////////////////////////////////////////////////////
1278 // End of subsystem initialization.
1279 ////////////////////////////////////////////////////////////////////
1280
1281 fgSetBool("/sim/crashed", false);
1282 fgSetBool("/sim/initialized", true);
1283
1284 SG_LOG( SG_GENERAL, SG_INFO, endl);
1285 }
1286
1287 // re-position is a simplified version of the traditional (legacy)
1288 // reset procedure. We only need to poke systems which will be upset by
1289 // a sudden change in aircraft position. Since this potentially includes
1290 // Nasal, we trigger the 'reinit' signal.
1291 void fgStartReposition()
1292 {
1293 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
1294 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
1295
1296 flightgear::addSentryBreadcrumb("start reposition", "info");
1297
1298 // ensure we are frozen
1299 bool freeze = master_freeze->getBoolValue();
1300 if ( !freeze ) {
1301 master_freeze->setBoolValue(true);
1302 }
1303
1304 // set this signal so Nasal scripts can take action.
1305 fgSetBool("/sim/signals/reinit", true);
1306 fgSetBool("/sim/crashed", false);
1307
1308 // Fetch the subsystem manager.
1309 auto mgr = globals->get_subsystem_mgr();
1310
1311 mgr->get_subsystem<FDMShell>()->unbind();
1312
1313 // update our position based on current presets
1314 // this will mark position as needed finalized which we'll do in the
1315 // main-loop
1316 flightgear::initPosition();
1317
1318 auto terraSync = mgr->get_subsystem<simgear::SGTerraSync>();
1319 if (terraSync) {
1320 terraSync->reposition();
1321 }
1322
1323 // Initialize the FDM
1324 mgr->get_subsystem<FDMShell>()->reinit();
1325
1326 // reset replay buffers
1327 mgr->get_subsystem<FGReplay>()->reinit();
1328
1329 // ugly: finalizePosition waits for METAR to arrive for the new airport.
1330 // we don't re-init the environment manager here, since historically we did
1331 // not, and doing so seems to have other issues. All that's needed is to
1332 // schedule METAR fetch immediately, so it's available for finalizePosition.
1333 // So we manually extract the METAR-fetching component inside the environment
1334 // manager, and re-init that.
1335 auto envMgr = static_cast<SGSubsystemGroup*>(mgr->get_subsystem<FGEnvironmentMgr>());
1336 if (envMgr) {
1337 envMgr->get_subsystem("realwx")->reinit();
1338 }
1339
1340 // needed for parking assignment to work after reposition
1341 auto atcManager = mgr->get_subsystem<FGATCManager>();
1342 if (atcManager) {
1343 atcManager->reposition();
1344 }
1345
1346 // need to bind FDMshell again
1347 mgr->get_subsystem<FDMShell>()->bind();
1348
1349 // need to reset aircraft (systems/instruments/autopilot)
1350 // so they can adapt to current environment
1351 mgr->get_subsystem<FGSystemMgr>()->reinit();
1352 mgr->get_subsystem<FGInstrumentMgr>()->reinit();
1353 mgr->get_subsystem("xml-autopilot")->reinit();
1354
1355 // need to update the timezone
1356 auto timeManager = mgr->get_subsystem<TimeManager>();
1357 if (timeManager) {
1358 timeManager->reposition();
1359 }
1360
1361 // setup state to end re-init
1362 fgSetBool("/sim/signals/reinit", false);
1363 if ( !freeze ) {
1364 master_freeze->setBoolValue(false);
1365 }
1366 fgSetBool("/sim/sceneryloaded",false);
1367 flightgear::addSentryBreadcrumb("end of reposition", "info");
1368 }
1369
1370 void fgStartNewReset()
1371 {
1372 flightgear::updateSentryTag("have-reset", "yes");
1373
1374 // save user settings now, so that USERARCHIVE-d values changes since the
1375 // last init are recorded and hence re-loaded when we fgInitConfig down
1376 // later in this function. Otherwise all such settings are lost.
1377 globals->saveUserSettings();
1378
1379 SGPropertyNode_ptr preserved(new SGPropertyNode);
1380
1381 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1382 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1383
1384 fgSetBool("/sim/signals/reinit", true);
1385 fgSetBool("/sim/freeze/master", true);
1386
1387 // pause the osgDB requests right now, but more may appear; we will
1388 // clear and cancel further down once shutdown has occured
1389 FGRenderer* render = globals->get_renderer();
1390 auto pager = render->getView()->getDatabasePager();
1391 pager->setAcceptNewDatabaseRequests(false);
1392 pager->cancel();
1393
1394 // extra clear is needed to ensure compile/merge lists are also empty
1395 pager->clear();
1396
1397 assert(pager->getDataToMergeListSize() == 0);
1398 assert(pager->getDataToCompileListSize() == 0);
1399
1400
1401 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1402 // Nasal is added in fgPostInit, ensure it's already shutdown
1403 // before other subsystems, so Nasal listeners don't fire during shutdown
1404 subsystemManger->remove("nasal");
1405
1406 subsystemManger->shutdown();
1407 #ifdef ENABLE_OSGXR
1408 flightgear::VRManager::destroyInstance();
1409 #endif
1410 subsystemManger->unbind();
1411
1412 // hack fix for many reset crashes relating to the static instance
1413 // of this class. Will be fixed better for future versions by making
1414 // this a proper subsystem.
1415 //FGATCDialogNew::hackyReset();
1416
1417 // remove most subsystems, with a few exceptions.
1418 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1419 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1420 for (auto nm : grp->member_names()) {
1421 if ((nm == "time") || (nm == "terrasync") || (nm == "events")
1422 || (nm == "lighting")
1423 || (nm == FGScenery::staticSubsystemClassId())
1424 || (nm == flightgear::ErrorReporter::staticSubsystemClassId())
1425 )
1426 {
1427 continue;
1428 }
1429
1430 try {
1431 subsystemManger->remove(nm.c_str());
1432 } catch (std::exception& e) {
1433 SG_LOG(SG_GENERAL, SG_INFO, "caught " << e.what() << " << shutting down:" << nm);
1434 } catch (...) {
1435 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << nm);
1436 }
1437
1438 // don't delete here, dropping the ref should be sufficient
1439 }
1440 } // of top-level groups iteration
1441
1442 // drop any references to AI objects with TACAN
1443 flightgear::NavDataCache::instance()->clearDynamicPositioneds();
1444
1445 // needed or we crash in multi-threaded OSG mode
1446 render->getViewerBase()->stopThreading();
1447
1448 osg::ref_ptr<osgViewer::CompositeViewer> composite_viewer = render->getCompositeViewer();
1449 osg::ref_ptr<osgViewer::View> composite_viewer_view;
1450 if (composite_viewer) {
1451 composite_viewer_view = render->getView();
1452 }
1453
1454 // order is important here since tile-manager shutdown needs to
1455 // access the scenery object
1456 subsystemManger->remove(FGScenery::staticSubsystemClassId());
1457
1458 FGScenery::getPagerSingleton()->clearRequests();
1459 flightgear::CameraGroup::setDefault(NULL);
1460
1461
1462 osgDB::Registry::instance()->clearObjectCache();
1463 // Pager requests depend on this, so don't clear it until now
1464 sgUserDataInit( NULL );
1465
1466 // preserve the event handler; re-creating it would entail fixing the
1467 // idle handler
1468 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1469 // tell the event handler to drop properties, etc
1470 eventHandler->clear();
1471
1472 globals->set_renderer(NULL);
1473 globals->set_matlib(NULL);
1474
1475 flightgear::unregisterMainLoopProperties();
1476 FGReplay::resetStatisticsProperties();
1477
1478 simgear::clearEffectCache();
1479 simgear::VPBTechnique::clearConstraints();
1480 simgear::SGModelLib::resetPropertyRoot();
1481 simgear::ParticlesGlobalManager::clear();
1482 simgear::UniformFactory::instance()->reset();
1483
1484 flightgear::addons::AddonManager::reset();
1485
1486 globals->resetPropertyRoot();
1487 // otherwise channels are duplicated
1488 globals->get_channel_options_list()->clear();
1489
1490 // IMPORTANT
1491 // this is the low-water mark of the reset process.
1492 // Subsystems (except the special ones), properties, OSG nodes, Effects
1493 // should all be gone at this, except for special things, such as the
1494 // splash node.
1495 // From here onwards we're recreating early parts of main/init, before
1496 // we restart the main loop.
1497 // This is the place to check that instances of classes have all be
1498 // cleaned up correctly. (Also, the OSG threads are all paused, we're back
1499 // in single threaded mode)
1500 /////////////////////
1501
1502 flightgear::addons::AddonManager::createInstance();
1503
1504 fgInitConfig(0, NULL, true);
1505 fgInitGeneral(); // all of this?
1506
1507 // set out new property root on the command manager
1508 SGCommandMgr::instance()->setImplicitRoot(globals->get_props());
1509
1510 flightgear::Options::sharedInstance()->processOptions();
1511
1512 // Rebuild the lists of allowed paths for cases where a path comes from an
1513 // untrusted source, such as the global property tree (this uses $FG_HOME
1514 // and other paths set by Options::processOptions()).
1515 fgInitAllowedPaths();
1516
1517 const auto& resMgr = simgear::EmbeddedResourceManager::instance();
1518 // The language was (re)set in processOptions()
1519 const string locale = globals->get_locale()->getPreferredLanguage();
1520 resMgr->selectLocale(locale);
1521 SG_LOG(SG_GENERAL, SG_INFO,
1522 "EmbeddedResourceManager: selected locale '" << locale << "'");
1523
1524 // PRESERVED properties over-write state from options, intentionally
1525 if ( copyProperties(preserved, globals->get_props()) ) {
1526 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1527 } else {
1528 SG_LOG( SG_GENERAL, SG_INFO,
1529 "Some errors restoring preserved state (read-only props?)" );
1530 }
1531
1532 fgInitAircraftPaths(true);
1533 fgInitAircraft(true, false /* not from launcher */);
1534
1535 auto presets = globals->get_subsystem_mgr()->add<flightgear::GraphicsPresets>();
1536 presets->applyInitialPreset();
1537
1538 render = new FGRenderer(composite_viewer);
1539 render->setEventHandler(eventHandler);
1540 eventHandler->reset();
1541 globals->set_renderer(render);
1542 render->init();
1543
1544 if (composite_viewer) {
1545 render->setView(composite_viewer_view);
1546 }
1547 else {
1548 render->setView(viewer.get());
1549 }
1550
1551 sgUserDataInit( globals->get_props() );
1552
1553 unsigned int numDBPagerThreads = std::max(fgGetNode("/sim/rendering/database-pager/threads", true)->getIntValue(1), 1);
1554
1555 if (composite_viewer) {
1556 composite_viewer_view->setDatabasePager(FGScenery::getPagerSingleton());
1557 composite_viewer_view->getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true, false);
1558 composite_viewer_view->getDatabasePager()->setUpThreads(numDBPagerThreads, 0);
1559 composite_viewer_view->getDatabasePager()->setAcceptNewDatabaseRequests(true);
1560 flightgear::CameraGroup::buildDefaultGroup(composite_viewer_view);
1561 composite_viewer_view->setFrameStamp(composite_viewer->getFrameStamp());
1562 osg::GraphicsContext::createNewContextID();
1563
1564 #ifdef ENABLE_OSGXR
1565 // After buildDefaultGroup (which puts used graphics contexts into viewer)
1566 // Before threading re-enabled
1567 flightgear::VRManager::instance()->reset();
1568 #endif
1569
1570 render->setView(composite_viewer_view);
1571 render->preinit();
1572 composite_viewer->startThreading();
1573 }
1574 else {
1575 viewer->getDatabasePager()->setUpThreads(numDBPagerThreads, 0);
1576 viewer->getDatabasePager()->setAcceptNewDatabaseRequests(true);
1577 // must do this before preinit for Rembrandthe
1578 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1579 render->preinit();
1580 viewer->startThreading();
1581 }
1582
1583 fgOSResetProperties();
1584
1585 // init some things manually
1586 // which do not follow the regular init pattern
1587
1588 globals->get_event_mgr()->init();
1589 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1590
1591 globals->set_matlib( new SGMaterialLib );
1592
1593 // terra-sync needs the property tree root, pass it back in
1594 auto terra_sync = subsystemManger->get_subsystem<simgear::SGTerraSync>();
1595 if (terra_sync) {
1596 terra_sync->setRoot(globals->get_props());
1597 }
1598
1599 fgSetBool("/sim/signals/reinit", false);
1600 fgSetBool("/sim/freeze/master", false);
1601 fgSetBool("/sim/sceneryloaded",false);
1602
1603 flightgear::addSentryBreadcrumb("end of reset", "info");
1604 }
1605
1606 void fgInitPackageRoot()
1607 {
1608 if (globals->packageRoot()) {
1609 return;
1610 }
1611
1612 SGPath packageAircraftDir = flightgear::Options::sharedInstance()->actualDownloadDir();
1613 packageAircraftDir.append("Aircraft");
1614
1615 SG_LOG(SG_GENERAL, SG_INFO, "init package root at:" << packageAircraftDir);
1616
1617 SGSharedPtr<Root> pkgRoot(new Root(packageAircraftDir, FLIGHTGEAR_VERSION));
1618 // set the http client later (too early in startup right now)
1619 globals->setPackageRoot(pkgRoot);
1620
1621 }
1622
1623 int fgUninstall()
1624 {
1625 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
1626 simgear::Dir fgHome(dataPath);
1627 if (fgHome.exists()) {
1628 if (!fgHome.remove(true /* recursive */)) {
1629 fprintf(stderr, "Errors occurred trying to remove FG_HOME");
1630 return EXIT_FAILURE;
1631 }
1632 }
1633
1634 if (fgHome.exists()) {
1635 fprintf(stderr, "unable to remove FG_HOME");
1636 return EXIT_FAILURE;
1637 }
1638
1639 #if defined(SG_WINDOWS)
1640 SGPath p = flightgear::defaultDownloadDir();
1641 // we don't want to remove the whole dir, let's nuke specific
1642 // subdirs which are (hopefully) safe
1643
1644 SGPath terrasyncPath = p / "TerraSync";
1645 if (terrasyncPath.exists()) {
1646 simgear::Dir dir(terrasyncPath);
1647 if (!dir.remove(true /*recursive*/)) {
1648 std::cerr << "Errors occurred trying to remove " << terrasyncPath << std::endl;
1649 }
1650 }
1651
1652 SGPath packagesPath = p / "Aircraft";
1653 if (packagesPath.exists()) {
1654 simgear::Dir dir(packagesPath);
1655 if (!dir.remove(true /*recursive*/)) {
1656 std::cerr << "Errors occurred trying to remove " << packagesPath << std::endl;
1657 }
1658 }
1659
1660 SGPath cachePath = p / "TextureCache";
1661 if (cachePath.exists()) {
1662 simgear::Dir dir(cachePath);
1663 if (!dir.remove(true /*recursive*/)) {
1664 std::cerr << "Errors occurred trying to remove " << cachePath << std::endl;
1665 }
1666 }
1667 #endif
1668 return EXIT_SUCCESS;
1669 }