18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 11:15:23 +01:00
Files
maszyna/application/application.cpp
jerrrrycho ed8708c5e2 feat(simulation): snapshots, save the state of a running scenery and load it back (stage A) (#420)
* feat(simulation): text format of simulation snapshots

A snapshot of a running simulation is a text file in the syntax of the scenery
files: entries of the form <type> <name> <key> <value> ... end<type>, the first
one a header which names the scenery. This is the text alone: entries, writer,
reader, the names of the things of a scenery, the plan of coupling changes and
the command line switches (--load-snapshot, --snapshot-at), in the core library
with unit tests. Nothing reads or writes a snapshot yet.

* feat(simulation): snapshot of time, weather, cells, switches and events (L1)

--snapshot-at <seconds> <file> writes a snapshot when the simulation has run
that long, --load-snapshot <file> puts one over the scenery once it has loaded,
before the first frame. This layer keeps the clock and the simulation timer,
the weather with the wind, the random engine, the memory cells, the switches,
the tracks an event can change and the ones made on the run, the traction
power sources, the event queue, the timers of the launchers and the lamps of
the signals.

While a snapshot is put back the event manager is suspended, so nothing in the
scenery reacts to it. Existing classes only get accessors for what was private
(the fraction of the second, launcher timers, the speed limit of a track, the
wind, the state of a power source, the event queue). Without the switches
nothing changes.

* feat(simulation): state of a vehicle's physics for snapshots (L3, core)

What TMoverParameters holds of a running vehicle, to and from an entry of a
snapshot: speed, load, controls, switches and relays, pantographs, doors,
engine and its cooling, the air of the pipes, of every reservoir of the brake
valve (with the flow it has yet to take in) and of the chambers of the driver's
valves, the vigilance device, the power circuits. In the core library, tested
on the real vehicle definitions: a
vehicle restored on a fresh one saves the same, and runs on next to the one it
was saved from.

The brake valves, the driver's valves and the vigilance device get accessors
for their private state (reservoirs(), latches(), pressures(), state()), a
reservoir one for the flow it has yet to take in; nothing else in the physics
changes. This comes before the vehicles of the scenery (L2), whose
speed and load are kept by it.

* feat(simulation): snapshot of vehicles and consists (L2)

Every vehicle is kept with the place of both its axles (track, distance,
direction, path of a switch, events still to set off), the way it faces, its
couplings with their flags, destination and, through its physics, speed and
load. Loaded, the vehicles are put straight where they were
(TTrackFollower::Place(), which trails no switch and fires no event), then
parted and joined until they are coupled as saved, whatever trainsets the
scenery made of them.

A vehicle of the snapshot the scenery does not have is skipped and reported,
one the snapshot does not know stays as the scenery made it, one which had left
the simulation is taken out again.

* feat(simulation): pantographs and passenger exchange in snapshots (L3)

What a vehicle keeps of its machinery beside its physics: the arms of the
pantographs as they stand under the wire, the time without voltage, the
passengers getting on and off, the lighting of the compartments, the headlight
toggles, the last force asked of the electrodynamic brake.

* feat(simulation): snapshot of the drivers and of the player's vehicle (L4)

A driver is kept with its orders and the one it is on, the name of its
timetable and its place in it, the consist it has, what it holds to (speeds of
signals and limits, the reason it stands, its timers and flags), its table of
what is ahead on the track with the point limits it has latched, its tables of
what the brake of the consist gives, and whether the AI drives. A driver who
had moved to another vehicle of its train is moved there.

A run loaded in ghost view (the test mode) is ready before its first frame, as
the run it goes on from was.

The snapshot also names the vehicle the player was in, which --load-snapshot
starts in unless -v says otherwise.

* feat(simulation): snapshotsave command, on [Ctrl]+[Shift]+[F9]

Writes a snapshot of the simulation to snapshots/<scenery>_<date>_<time>.snapshot
in the game folder. The command is the last one of the list, so the numbers of
the others stay.

* test: scenario cases which load a simulation snapshot and compare the run

A case with a "snapshot" section runs its scenery to a time, taking snapshots
on the way and at the end, then again from the first snapshot, and compares the
two ends: positions, speeds, pressures, couplings, cells, switches, drivers.
The snapshot saved right after loading has to be the one loaded.
tests/scenarios/snapshots.py reads the format and tells two snapshots apart.
The switches and the format are described in tests/scenarios/README.md.

* fix(simulation): a vehicle gone in the snapshot leaves its isolated sections

The scenery counts the axles of every vehicle in the isolated sections of
the tracks it puts it on. A vehicle the snapshot has as removed was only
taken off the list of its track, so its two axles stayed counted there and
the section never went free again: the next train on it went 4-6-4 axles
instead of 0-2-0, and its busy and free events never fired.

- A removed vehicle counts both axles out of the sections of their tracks,
  is taken off the list of its track only if it's on it, and has no owner.
- The drivers a snapshot doesn't have are deleted as before, and no
  vehicle keeps its owner pointing at one of them.
- The snapshot keeps the count of every isolated section and sets it after
  the vehicles are placed: the vehicles a consist leaves behind as it goes
  through a portal stay counted where they were, in the game too. A count
  the placing gives other than the snapshot has is told in the log.
- A vehicle with two entries is placed once.
- TIsolated::axles() reads and sets the count.
- The harness compares the counts of the sections; a new case,
  snapshot_td_portal_isolated, has a train leave through a portal from the
  track of a section before the snapshot.

* fix(simulation): every value of a snapshot file is checked before it's used

A damaged or edited snapshot could put an index past a table, a count
which takes forever or a number out of the range of its type into the
simulation, and a file cut short was put back half way.

- Reading a value: a whole number has to be whole and fit its type (an
  enum its underlying one), a float can't be past its largest value; what
  doesn't fit is refused. Every refusal names the entry, the key and the
  value, and goes to the log (errors.txt), up to 100 lines and a count.
- Ranges: coupler ends 0 or 1 and the flags of a coupling; couplings which
  would close a ring of vehicles; the count of the points of a driver's
  table and of its point limits (not past the keys of the entry), the
  indices into the table (tablelast, semnext, semnextstop); the order
  stack and its position, the timetable station, the driver's enums and
  directions; the path, events and distance of an axle, facing and first
  axle; the date and time; switch states, made track ends, crossing
  segments, event siblings and times, launcher timers, the weather; the
  load (amount, and a name which isn't a path); the whole numbers inside
  number lists (flags of a table point, the stop of a coupler pair, the
  track flags under a vehicle, the fuse count of a power source, the cab
  of the vigilance device).
- The positions of the controllers are brought within the ranges of the
  vehicle: master and secondary controller (set and actual), reverser,
  cabs, light, compressor and wiper switches, brake handle, hand brake,
  dimmer.
- A document with problems isn't loaded unless --load-snapshot-force says
  so; a test run ends with the error code then. The header counts the
  entries, so a file cut between two entries is found too. A file of a
  newer version is a warning, not a problem.
- A snapshot is written to <file>.tmp and renamed over the file only when
  the stream didn't fail.
- Unit tests of the reader on damaged input.

* feat(simulation): the pullee mode and the holding brake timer in snapshots

Of what #419 and #424 added to TMoverParameters, two are state: PulleeMode
(prepared for being hauled dead; the scenery sets it, PulleeModeSwitch()
can change it) and StopBrakeReleaseTimer (how long power has been asked
for, which lets the holding brake of a unit go after its delay). Both are
kept now, as "pulleemode" and "stopbrakereleasetimer". The others
(PressureSwitchBrakeCylinder, EmergencyBrakeMainOffPressure,
StopBrakeReleaseDelay) come from the vehicle definition and aren't.

* fix(simulation): the snapshot code without Sonar issues

No declaration shadows an enumerator, the variables used only by a
condition are declared in it, write_file takes its writer as a template,
the temporary file is a std::filesystem::path, the isolated sections are
looked up by a transparent hash, apply_couplings is split into helpers,
and the copies of the simulation's random engine are marked NOSONAR.
The test data has no http:// in it. No snapshot key or format changes.

* fix(brakes): TSt113 lists the control pressure once

TSt113::pressures() added CP on top of TH14K1::pressures(), which
already has it since #366 removed the CP of TSt113 that hid it. A
snapshot held the St113's control chamber twice. The second entry is
removed.

Tests: every driver's handle lists each pressure once, and the St113
pressures of an EN57 saved through a snapshot come back on a fresh one.

* fix(simulation): snapshots skip road traffic, refuse changed sceneries, keep misplaced vehicles apart

Cars of the road spawn points which a snapshot has on the road are no longer put back: the spawn point owns
them and the snapshot would leave them frozen on the track. They're counted in the log. The pooled cars keep
their AI drivers, which the snapshot used to delete.

A snapshot whose scenery fingerprint differs is refused unless --load-snapshot-force is given: tracks named
"#N" shift when a track is added. Each vehicle is checked against the x/y/z of its entry after placing. One
more than 1 m off, or one which can't be placed, goes back where the scenery put it, isn't coupled to the
placed vehicles, and keeps its scenery state and driver.

Couplings set from a snapshot keep to CompatibleCoupling, so no MU control between an electric and a diesel
loco (#520).

The snapshotsave key writes to snapshotsdir of eu07.ini (snapshots by default, ini only like screenshotsdir),
adds _2, _3... to a name that is taken, and shows where the file went.

* refactor(simulation): the snapshot reads and writes the private state of the vehicles through their own members

Since #552 the state of physics::Vehicle and of its parts is private, and since #531 the vehicle, the AI
and the cab live in other files under other names. The snapshot code is ported to that:

- the state of a vehicle's physics is saved and loaded by physics::Vehicle::SnapshotSave() and
  SnapshotLoad() (physics/components/snapshot.cpp), with the tables of the variables in a nested
  snapshot_members; capture_mover() and apply_mover() only hand it the entry. The parts with private
  state (low voltage, line breaker, line contactors, protective relays, converter, air of the
  pantographs, compressor, air supply) give a plain Snapshot of it and take it back
  (TakeSnapshot(), RestoreSnapshot()); the rest goes through their queries and setters
- the keys, their order and the numbers in them are unchanged, so the snapshots written before load:
  the fields that moved into the parts are mapped there (Mains to lineBreaker, PipePress to brakePipe,
  BrakeCtrlPos to brakes, dizel_* to diesel, hydro_* to torqueConverter and retarder, eimv to
  inductionMotor.state in the order of the old table, EngDmgFlag to equipmentFaults, ...)
- TDynamicObject: the machinery of a vehicle (sections, rail joints, the passenger exchange) is saved
  by members of its own, as these are private now; MED_oldFED is the last ED demand of the consist's
  brake blending (ConsistBrakeBlending::LastElectrodynamicDemand())
- TController: the driving flags are saved as the bits of iDrivigFlags they were, the running brake
  test as the number of its stage, the uphill start and the braking shortfall from their structs;
  StaticBrakeTest, which is gone, is written as 0 and not read
- the couplings take Coupling, CouplingSet and VehicleEnd; orders are DriverOrders
- the unit tests of the snapshot of a vehicle use the queries and the parts

* fix(simulation): carry the driver's coupling set in the snapshot as the bits of the set

iCoupler is a CouplingSet since 2098614f, which record::set()/get() can't take. It goes
through the converted values as a whole number, as the driving flags do: Bits() on save,
CouplingSet::FromBits() on load. The key and its values are the same as before.

* fix(simulation): a loaded snapshot counts the vehicles it left where they stand

apply_isolated() set every isolated section to the count of the snapshot, also where a
vehicle the load left at its scenery place (misplaced, forced load, road traffic not put
back) stands, or where the snapshot had it. The axles of those vehicles are now counted in
the sections they stand in and out of the ones the snapshot has them in, and the memory
cells of those sections say whether they are taken by that count.

An AI consist doesn't end on a vehicle the load left: the ends are then found along what is
coupled now, as CheckVehicles() finds them.

The player entry no longer writes the cab, which nothing read: the cab is the one the
vehicle has occupied (caboccupied of its entry).

* feat(simulation): the snapshot keeps a derailment and the brakes of a sleeping vehicle

A derailed vehicle came back on the rails. Its entry now keeps what derailed it (outcome,
cause, speed, the cause and side of the motion off the track, the acceleration, the
collision derailment) and the distance its criteria were last checked over; the
derailment the scenery and the test mode were told of (new_derailment()), so it isn't told
again; and with physics.derailment new the motion of the body off the track
(derail_motion::body::state()) with the timers of the vehicle off the track. The terrain
under it is gathered anew around it when it loads.

sleep_brakes, what a sleeping vehicle's brake force came from, is kept too.

All keys are new: an entry without them leaves the vehicle as the scenery made it, so files
written before still load. New scenario case snapshot_td_off_track.

* fix(simulation): the snapshot keeps the sanded start of an AI driver

#494 (in staging since the last runs of the snapshot cases) made a driver whose start
slipped keep sanding under power until the train is under way, and take the power down a
step at a time. Neither the flag nor the time of the last step down was kept, so on
linia61 the loaded run sanded one frame later than the run which went on and parted from
it 0.06 s after loading (suwnica2, 9 mm and 0.08 km/h at 600 s). Both are kept now
(sandedstart, sandedstarttime); an entry without them leaves the driver as it is.

* fix(simulation): the snapshot keeps a train running forked on a switch thrown under it

Staging's switch fork running (#496) gave the axles and the vehicles state of their own: the way of a
switch an axle ran onto (TTrackFollower::iPath, which it leaves the switch by after a throw), the ways it
remembers of the switches behind it (path_memory, read when the axle behind it comes onto one of them),
and per vehicle the switch its bogies or its coupled ends run forked on with whether that was told
(m_forkbogies, m_forkends). None of it was in a snapshot: a loaded train on a switch thrown under it
would have left it by the way it is set now and never derailed running forked.

- Place() sets the way of the switch from the path the axle is put on, as SetCurrentTrack() does, and
  clears the facing entry the vehicle hasn't looked at (there is none between frames).
- A vehicle entry has the remembered ways of each axle, oldest first (axle0switch0, axle0way0...),
  recorded again into an empty memory on load (path_memory::entries()), and the forked watches
  (forkbogies, fork0, fork1 with their "told"). A name which isn't a switch is refused.
- New case snapshot_td_switch_thrown: the snapshot is taken while the second coach of
  eu07_td_switch_thrown_facing_behind_derails runs forked and hasn't derailed yet; the loaded run derails
  it the same way and the two files at 150 s are identical.
2026-12-02 15:40:25 +01:00

1895 lines
54 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "application/application.h"
#include "application/drivermode.h"
#include "application/editormode.h"
#include "application/scenarioloadermode.h"
#include "launcher/launchermode.h"
#include "utilities/Globals.h"
#include "utilities/utilities.h"
#include "simulation/simulation.h"
#include "simulation/simulationsounds.h"
#include "simulation/blackboxrecorder.h"
#include "vehicle/Train.h"
#include "utilities/dictionary.h"
#include "scene/sceneeditor.h"
#include "rendering/renderer.h"
#include "application/uilayer.h"
#include "utilities/Logs.h"
#include "utilities/logfiles.h"
#include "world/SleeperWorker.h"
#include "rendering/screenshot.h"
#include "utilities/translation.h"
#include "vehicle/Train.h"
#include "utilities/Timer.h"
#include "utilities/memorystats.h"
#include "utilities/framepacer.h"
#include "utilities/hardwareprobe.h"
#include "utilities/dictionary.h"
#include "version_info.h"
#include "simulation/simulationtest.h"
#include "simulation/simulationsnapshotworld.h"
#include "utilities/physicslog.h"
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "utilities/translation.h"
#include "physics/vehicle.h"
#if WITH_DISCORD_RPC
#include "ref/discord-rpc/include/discord_rpc.h"
#include <discord_rpc.h>
#endif
#include <chrono>
#include "utilities/translation.h"
#ifdef _WIN32
#pragma comment(lib, "dsound.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "setupapi.lib")
#pragma comment(lib, "dbghelp.lib")
#pragma comment(lib, "version.lib")
#include <timeapi.h>
#endif
#ifdef __unix__
#include <unistd.h>
#include <sys/stat.h>
#endif
eu07_application Application;
screenshot_manager screenshot_man;
ui_layer uilayerstaticinitializer;
namespace
{
#ifdef _WIN32
// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms.
// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up
// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or
// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the
// main loop, as it costs some power for as long as it's held
bool timer_period_set{false};
#endif
// asks for the finer timer once, when fpslimit is set
void begin_timer_period()
{
#ifdef _WIN32
if (!timer_period_set && Global.minframetime.count() > 0.f)
timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR);
#endif
}
void end_timer_period()
{
#ifdef _WIN32
if (timer_period_set)
timeEndPeriod(1);
timer_period_set = false;
#endif
}
// debug.perflog: every so many seconds the tables of the debug panel of the renderer, its times on the cpu and the gpu by the pass
// and its counts of the draws, appended to perf.txt beside the log (emptied at the first write of the run), to tell what slows the
// frame down while the game runs
void write_performance_log()
{
if ((Global.debug_perflog <= 0.f) || (GfxRenderer == nullptr) || (false == simulation::is_ready))
return;
// the frames between two writes: the longest and how many took long, which the averages of the tables don't show
static auto last{std::chrono::steady_clock::now()};
static auto next{last + std::chrono::seconds(5)};
static bool started{false};
static double longest{0.0};
static int slow{0};
static int stalled{0};
static int frames{0};
auto const now{std::chrono::steady_clock::now()};
auto const frame{std::chrono::duration<double, std::milli>(now - last).count()};
last = now;
longest = std::max(longest, frame);
slow += (frame > 25.0 ? 1 : 0);
stalled += (frame > 50.0 ? 1 : 0);
++frames;
if (now < next)
return;
next = now + std::chrono::milliseconds(static_cast<long long>(Global.debug_perflog * 1000.f));
std::ofstream out{"perf.txt", started ? std::ios::app : std::ios::trunc};
started = true;
out << std::format("==== {:.1f} s, {} frames, the longest {:.1f} ms, {} over 25 ms, {} over 50 ms\n", Timer::GetTime(), frames, longest, slow, stalled);
longest = 0.0;
slow = 0;
stalled = 0;
frames = 0;
out << GfxRenderer->info_times() << "\n" << GfxRenderer->info_stats() << "\n";
}
} // namespace
#ifdef _WIN32
extern "C"
{
GLFWAPI HWND glfwGetWin32Window(GLFWwindow *window);
}
LRESULT APIENTRY WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
extern HWND Hwnd;
extern WNDPROC BaseWindowProc;
#endif
// user input callbacks
void focus_callback(GLFWwindow *window, int focus)
{
ui_layer::focus_callback(focus);
Application.on_focus_change(focus != 0);
}
void cursor_enter_callback(GLFWwindow *window, int entered)
{
if (scripted_input::driving())
return;
ui_layer::cursor_enter_callback(entered);
}
void framebuffer_resize_callback(GLFWwindow *, int w, int h)
{
Global.fb_size = glm::ivec2(w, h);
}
void window_resize_callback(GLFWwindow *, int w, int h)
{
Global.window_size = glm::ivec2(w, h);
Application.on_window_resize(w, h);
}
void cursor_pos_callback(GLFWwindow *window, double x, double y)
{
if (scripted_input::driving())
return;
ui_layer::cursor_pos_callback(x, y);
Global.cursor_pos = glm::ivec2(x, y);
Application.on_cursor_pos(x, y);
}
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods)
{
if (scripted_input::driving())
return;
Application.on_mouse_button(button, action, mods);
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset)
{
if (scripted_input::driving())
return;
Application.on_scroll(xoffset, yoffset);
}
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (scripted_input::driving())
return;
Application.on_key(key, scancode, action, mods);
}
void char_callback(GLFWwindow *window, unsigned int c)
{
if (scripted_input::driving())
return;
Application.on_char(c);
}
namespace
{
// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no
// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context,
// is told once. glfw may call this from any thread that uses it
void glfw_error_callback(int const Code, char const *Description)
{
auto message{std::format("GLFW error 0x{:08X}: {}", static_cast<unsigned int>(Code), Description != nullptr ? Description : "(no description)")};
static std::mutex reportedmutex;
static std::set<std::string> reported;
{
std::scoped_lock lock(reportedmutex);
if (false == reported.insert(message).second)
return;
}
ErrorLog(message);
}
#ifdef WITH_CRASHPAD
// there while the renderer starts (init_gfx()): left behind by a start which crashed in it
constexpr char const *GFX_START_MARK{"crashdumps/gfx_start.pending"};
#endif
// the mark of the start of the renderer put down (Starting) or taken away
void mark_gfx_start(bool const Starting)
{
#ifdef WITH_CRASHPAD
std::error_code error;
if (Starting)
{
std::ofstream mark(GFX_START_MARK, std::ios::trunc);
}
else
{
std::filesystem::remove(GFX_START_MARK, error);
}
#else
(void)Starting;
#endif
}
// the question about the report of the last crash, asked before the renderer starts when that crash came while it started: the window
// of the question is drawn by the renderer (run_crashgui()), so a crash in its start, which repeats at every start, would never let it
// show. a box of the system asks instead, on Windows, where the reports are made
void ask_crash_report_before_gfx()
{
#if defined(WITH_CRASHPAD) && defined(_WIN32)
std::error_code error;
if ((false == crashreport_is_pending()) || Global.test.enabled || (false == std::filesystem::exists(GFX_START_MARK, error)))
{
return;
}
auto const polish{Global.asLang == "pl"};
auto const *text{
polish ? L"Podczas ostatniego uruchomienia symulator uległ awarii przy uruchamianiu grafiki.\nWysłać raport o błędzie do deweloperów?" :
L"The simulator crashed while starting the graphics during the last launch.\nSend the crash report to the developers?"};
auto const *caption{polish ? L"Raportowanie błędów" : L"Crash reporting"};
if (::MessageBoxW(nullptr, text, caption, MB_YESNO | MB_ICONERROR) == IDYES)
{
crashreport_upload_accept();
}
else
{
crashreport_upload_reject();
}
#endif
}
} // namespace
// public:
void eu07_application::queue_screenshot()
{
m_screenshot_queued = true;
}
int eu07_application::run_crashgui()
{
bool autoup = false;
bool y{false}, n{false};
// the questions are the ui of the frames the renderer draws (render_ui()), whichever api it is: the window has no opengl
// context with vulkan
m_crashui = [&]() {
ui_layer::begin_ui_frame_internal();
if (Global.asLang == "pl")
{
ImGui::Begin("Raportowanie błędów", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize);
ImGui::TextUnformatted("Podczas ostatniego uruchomienia symulatora wystąpił błąd.\nWysłać raport o błędzie do deweloperów?\n");
ImGui::TextUnformatted(("Usługa udostępniana przez " + crashreport_get_provider() + "\n").c_str());
y = ImGui::Button("Tak", ImVec2S(60, 0));
ImGui::SameLine();
ImGui::Checkbox("W przyszłości przesyłaj raporty o błędach automatycznie", &autoup);
ImGui::SameLine();
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::TextUnformatted("W celu wyłączenia tej funkcji będzie trzeba skasować plik crashdumps/autoupload_enabled.conf");
ImGui::EndTooltip();
}
ImGui::NewLine();
n = ImGui::Button("Nie", ImVec2S(60, 0));
ImGui::End();
}
else
{
ImGui::Begin("Crash reporting", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize);
ImGui::TextUnformatted("Crash occurred during last launch of the simulator.\nSend crash report to developers?\n");
ImGui::TextUnformatted(("Service provided by " + crashreport_get_provider() + "\n").c_str());
y = ImGui::Button("Yes", ImVec2S(60, 0));
ImGui::SameLine();
ImGui::Checkbox("In future send crash reports automatically", &autoup);
ImGui::SameLine();
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::TextUnformatted("To disable this feature remove file crashdumps/autoupload_enabled.conf");
ImGui::EndTooltip();
}
ImGui::NewLine();
n = ImGui::Button("No", ImVec2S(60, 0));
ImGui::End();
}
ui_layer::render_internal();
};
while (!glfwWindowShouldClose(m_windows.front()))
{
glfwPollEvents();
y = false;
n = false;
if (!GfxRenderer->Render())
break;
GfxRenderer->SwapBuffers();
if (y)
{
crashreport_upload_accept();
if (autoup)
crashreport_set_autoupload();
m_crashui = nullptr;
return 0;
}
if (n)
{
crashreport_upload_reject();
m_crashui = nullptr;
return 0;
}
}
m_crashui = nullptr;
// the player closed the window: the simulator closes with it, as it always has, but that is no failed start
return 1;
}
#if WITH_DISCORD_RPC
void eu07_application::DiscordRPCService()
{
// initialize discord-rpc
WriteLog("Initializing Discord Rich Presence...");
static const char *discord_app_id = "1343662664504840222";
DiscordEventHandlers handlers;
memset(&handlers, 0, sizeof(handlers));
Discord_Initialize(discord_app_id, &handlers, 1, nullptr);
// calculate startup timestamp
auto now = std::chrono::system_clock::now();
auto now_c = std::chrono::system_clock::to_time_t(now);
// Init RPC object
static DiscordRichPresence discord_rpc;
memset(&discord_rpc, 0, sizeof(discord_rpc));
discord_rpc.startTimestamp = static_cast<int64_t>(now_c);
discord_rpc.largeImageText = "MaSzyna";
// run loop
while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty() && !Global.applicationQuitOrder)
{
auto currentMode = m_modestack.top();
if (currentMode == mode::launcher)
{
// in launcher mode
discord_rpc.state = Translations.lookup_c("In main menu");
discord_rpc.details = Translations.lookup_c("Browsing scenarios...");
discord_rpc.largeImageKey = "";
discord_rpc.largeImageText = "MaSzyna";
// RPC upload
Discord_UpdatePresence(&discord_rpc);
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
continue;
}
else if (currentMode == mode::scenarioloader)
{
std::string rpcScnName = Global.SceneryFile;
if (rpcScnName[0] == '$')
rpcScnName.erase(0, 1);
rpcScnName.erase(rpcScnName.size() - 4, 4);
if (rpcScnName.find('_') != std::string::npos)
{
std::replace(rpcScnName.begin(), rpcScnName.end(), '_', ' ');
}
// realworld timestamp from datetime
static std::string state = Translations.lookup_s("Scenery: ") + rpcScnName;
discord_rpc.state = state.c_str();
discord_rpc.details = Translations.lookup_c("Loading scenery...");
discord_rpc.largeImageKey = "logo";
discord_rpc.largeImageText = "MaSzyna";
// RPC upload
Discord_UpdatePresence(&discord_rpc);
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
continue;
}
if (currentMode != mode::driver)
{
// the editor and the other modes: nothing to tell, without spinning a core on it
std::this_thread::sleep_for(std::chrono::milliseconds(250));
continue;
}
// Discord RPC updater
if (simulation::is_ready)
{
std::string PlayerVehicle;
if (simulation::Train != nullptr)
{
PlayerVehicle = simulation::Train->name();
// make to upper
for (auto &c : PlayerVehicle)
c = toupper(c);
PlayerVehicle = Translations.lookup_s("Driving: ") + PlayerVehicle;
discord_rpc.details = PlayerVehicle.c_str();
uint16_t playerTrainVelocity = simulation::Train->Dynamic()->GetVelocity();
if (playerTrainVelocity > 1)
{
// ikonka ze jedziemy i nie spimy
discord_rpc.smallImageKey = "driving";
std::string smallText = Translations.lookup_s("Speed: ") + std::to_string(playerTrainVelocity) + " km/h";
discord_rpc.smallImageText = smallText.c_str();
}
else
{
// krecimy postoj
discord_rpc.smallImageKey = "halt";
discord_rpc.smallImageText = Translations.lookup_c("Stopped");
}
}
Discord_UpdatePresence(&discord_rpc);
}
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
}
Discord_Shutdown();
}
#endif
int eu07_application::init(int Argc, char *Argv[])
{
int result{0};
// a test run is known before anything is logged: whoever started it reads its result on the standard output,
// which the log isn't written to then (eu07/maszyna#541)
Global.test.enabled = simulation::parse_test_command_line(std::vector<char const *>(Argv, Argv + Argc)).enabled;
// start logging service
std::thread sLoggingService(LogService);
Global.threads.emplace("LogService", std::move(sLoggingService));
init_debug();
result = init_settings(Argc, Argv);
// the log files are named by the settings (multiplelogs), so they are cleared and opened once those are read
init_files();
if (result != 0)
{
ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?");
return result;
}
// fpslimit is known now
begin_timer_period();
// the run's seed, settled once and kept in Globals: the engines come out of it.
// narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is
// the seed somebody can write down and pass on
if (false == Global.random_seed_given)
Global.random_seed = static_cast<std::uint32_t>(true_random_seed());
Global.random_engine.seed(Global.random_seed);
Global.local_random_engine.seed(Global.random_seed);
// configure the OS console according to Globals.ShowSystemConsole.
// must run AFTER init_settings (so the ini-loaded value is honoured) and
// BEFORE the first WriteLog below (so colored \033[...] sequences emitted
// by utilities/Logs.cpp land in a console with VT processing enabled).
init_console();
WriteLog("Starting MaSzyna rail vehicle simulator (release: " + Global.asVersion + ")");
WriteLog("For online documentation and additional files refer to: http://eu07.pl");
WriteLog("Authors: Marcin_EU, McZapkie, ABu, Winger, Tolaris, nbmx, OLO_EU, Bart, Quark-t, "
"ShaXbee, Oli_EU, youBy, KURS90, Ra, hunter, szociu, Stele, Q, firleju and others");
if (!crashreport_get_provider().empty())
WriteLog("Crashdump analysis provided by " + crashreport_get_provider() + "\n");
{
WriteLog("// settings");
std::stringstream settingspipe;
Global.export_as_text(settingspipe);
WriteLog(settingspipe.str());
}
// the cpu, the memory and the graphics adapters, for the bug reports
hardware::log_system();
WriteLog("// startup");
if ((result = init_glfw()) != 0)
{
ErrorLog("Failed to initialize glfw!");
return result;
}
if ((result = init_locale()) != 0)
{
ErrorLog("Failed to initialize locales! Maybe you're missing lang directory?");
return result;
}
ask_crash_report_before_gfx();
mark_gfx_start(true);
if ((result = init_gfx()) != 0)
{
// a start which failed, not one which crashed
mark_gfx_start(false);
ErrorLog("Failed to initialize GFX!");
return result;
}
if ((result = init_ui()) != 0)
{ // ui now depends on activated renderer
mark_gfx_start(false);
ErrorLog("Failed to init UI!");
return result;
}
mark_gfx_start(false);
if (crashreport_is_pending() && false == Global.test.enabled)
{ // run crashgui as early as possible: it's drawn by the renderer
if ((result = run_crashgui()) != 0)
{
// above 0 the player closed the window, which is no error
if (result < 0)
ErrorLog("Failed to run crash gui!");
else
WriteLog("Crash report window closed, closing");
return result;
}
}
if ((result = init_audio()) != 0)
{
ErrorLog("Failed to initialize OpenAL");
return result;
}
if ((result = init_data()) != 0)
{
ErrorLog("Failed to load data/ contents! Maybe your installation is broken?");
return result;
}
crashreport_add_info("python_enabled", Global.python_enabled ? "yes" : "no");
if (Global.python_enabled)
{
m_taskqueue.init();
}
crashreport_add_info("luascreens_enabled", Global.luascreens_enabled ? "yes" : "no");
crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no");
if (Global.luascreens_enabled || Global.wasm_enabled)
{
m_screenqueue.init();
if (Global.screens_gpupost)
{
m_screenqueue.set_post_processor(GfxRenderer->Screen_post_processor());
}
}
if ((result = init_modes()) != 0)
{
ErrorLog("Failed to initialize game modes");
return result;
}
#if WITH_DISCORD_RPC
// Run DiscordRPC service
// not for a test run: it would show the test scenery as the player's presence, and hold up the closing
if (false == Global.test.enabled)
{
std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this);
Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC));
}
#endif
if (!init_network())
return -1;
// glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the
// platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key
// codes of its launchers), every frame
glfwSetErrorCallback(nullptr);
return result;
}
double eu07_application::generate_sync()
{
if (Timer::GetDeltaTime() == 0.0)
return 0.0;
double sync = 0.0;
for (const TDynamicObject *vehicle : simulation::Vehicles.sequence())
{
auto const pos{vehicle->GetPosition()};
sync += pos.x + pos.y + pos.z;
}
sync += Random(1.0, 100.0);
return sync;
}
void eu07_application::queue_quit(bool direct)
{
if (direct || !m_modes[m_modestack.top()]->is_command_processor())
{
glfwSetWindowShouldClose(m_windows[0], GLFW_TRUE);
return;
}
command_relay relay;
relay.post(user_command::quitsimulation, 0.0, 0.0, GLFW_PRESS, 0);
}
bool eu07_application::is_server() const
{
return m_network && m_network->servers;
}
bool eu07_application::is_client() const
{
return m_network && m_network->client;
}
int eu07_application::run()
{
auto frame{0};
frame_pacer framepacer;
Timer::subsystem.mainloop_period.start();
// main application loop
while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty())
{
// the time from one frame's start to the next, the wait for fpslimit included
Timer::subsystem.mainloop_period.stop();
Timer::subsystem.mainloop_period.start();
Timer::subsystem.mainloop_total.start();
GfxRenderer->Frame_Start();
Timer::subsystem.loop_input.start();
glfwPollEvents();
if (m_headtrack)
m_headtrack->update();
Timer::subsystem.loop_input.stop();
Timer::subsystem.loop_ui_frame.start();
begin_ui_frame();
Timer::subsystem.loop_ui_frame.stop();
// -------------------------------------------------------------------
// multiplayer command relaying logic can seem a bit complex
//
// we are simultaneously:
// => master (not client) OR slave (client)
// => server OR not
//
// trivia: being client and server is possible
double frameStartTime = Timer::GetTime();
if (m_modes[m_modestack.top()]->is_command_processor())
{
// active mode is doing real calculations (e.g. drivermode)
int loop_remaining = MAX_NETWORK_PER_FRAME;
while (--loop_remaining > 0)
{
command_queue::commands_map commands_to_exec;
command_queue::commands_map local_commands = simulation::Commands.pop_intercept_queue();
double slave_sync{0.0};
// if we're the server
if (m_network && m_network->servers)
{
// fetch from network layer command requests received from clients
command_queue::commands_map remote_commands = m_network->servers->pop_commands();
// push these into local queue
add_to_dequemap(local_commands, remote_commands);
}
// if we're slave
if (m_network && m_network->client)
{
// fetch frame info from network layer,
auto frame_info = m_network->client->get_next_delta(MAX_NETWORK_PER_FRAME - loop_remaining);
// use delta and commands received from master
double delta = std::get<0>(frame_info);
Timer::set_delta_override(delta);
slave_sync = std::get<1>(frame_info);
add_to_dequemap(commands_to_exec, std::get<2>(frame_info));
// and send our local commands to master
m_network->client->send_commands(local_commands);
if (delta == 0.0)
loop_remaining = -1;
}
// if we're master
else
{
// just push local commands to execution
add_to_dequemap(commands_to_exec, local_commands);
loop_remaining = -1;
}
// send commands to command queue
simulation::Commands.push_commands(commands_to_exec);
// do actual frame processing (depending on mode)
if (!m_modes[m_modestack.top()]->update())
return 0;
// update continuous commands
simulation::Commands.update();
double sync = generate_sync();
// if we're the server
if (m_network && m_network->servers)
{
// send delta, sync, and commands we just executed to clients
double delta = Timer::GetDeltaTime();
double render = Timer::GetDeltaRenderTime();
m_network->servers->push_delta(render, delta, sync, commands_to_exec);
}
// if we're slave
if (m_network && m_network->client)
{
// verify sync
if (sync != slave_sync) // NOSONAR slave_sync is initialised, the PR analysis keeps a stale report of the old declaration
{
WriteLog("net: desync! calculated: " + std::to_string(sync) + ", received: " + std::to_string(slave_sync), logtype::net);
Global.desync = slave_sync - sync;
}
// set total delta for rendering code
double totalDelta = Timer::GetTime() - frameStartTime;
Timer::set_delta_override(totalDelta);
}
}
if (!loop_remaining)
{
// loop break forced by counter
float received = m_network->client->get_frame_counter();
float awaiting = m_network->client->get_awaiting_frames();
// TODO: don't meddle with mode progresbar
m_modes[m_modestack.top()]->set_progress(100.0f * (received - awaiting) / received);
}
else
{
m_modes[m_modestack.top()]->set_progress(0.0f, 0.0f);
}
}
else
{
// active mode is loader
// clear local command queue
simulation::Commands.pop_intercept_queue();
// do actual frame processing
if (!m_modes[m_modestack.top()]->update())
return 0;
}
// -------------------------------------------------------------------
// keep streamed terrain loaded around the active camera in every mode (editor + driver),
// once the simulation is live (avoid streaming while the scenery is still loading)
Timer::subsystem.loop_terrain.start();
if (simulation::is_ready && EditorTerrain.active())
EditorTerrain.update(Global.pCamera.Pos);
Timer::subsystem.loop_terrain.stop();
Timer::subsystem.loop_tasks.start();
m_taskqueue.update();
m_screenqueue.update();
Timer::subsystem.loop_tasks.stop();
if (!GfxRenderer->Render())
break;
GfxRenderer->SwapBuffers();
if (m_modestack.empty())
break;
m_modes[m_modestack.top()]->on_event_poll();
if (m_screenshot_queued)
{
m_screenshot_queued = false;
GfxRenderer->MakeScreenshot();
}
if (m_network)
m_network->update();
Timer::subsystem.mainloop_total.stop();
write_performance_log();
// fpslimit: wait for the next frame's slot (eu07/maszyna#416)
if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)})
{
// fpslimit may come from the config block of the scenery, read after the settings
begin_timer_period();
std::this_thread::sleep_until(*nextframe);
}
}
// Handled by application.exit
// Global.applicationQuitOrder = true;
// auto it = Global.threads.find("LogService");
// if (it != Global.threads.end())
// {
// if (it->second.joinable())
// it->second.join();
// }
//
// it = Global.threads.find("DiscordRPC");
// if (it != Global.threads.end())
// {
// if (it->second.joinable())
// it->second.join();
// }
return 0;
}
// issues request for a worker thread to perform specified task. returns: true if task was scheduled
bool eu07_application::request(python_taskqueue::task_request const &Task)
{
auto const result{m_taskqueue.insert(Task)};
if (false == result && Task.input != nullptr)
{
// clean up allocated resources since the worker won't
}
return result;
}
// ensures the main thread holds the python gil and can safely execute python calls
void eu07_application::acquire_python_lock()
{
m_taskqueue.acquire_lock();
}
// frees the python gil and swaps out the main thread
void eu07_application::release_python_lock()
{
m_taskqueue.release_lock();
}
void eu07_application::exit()
{
Global.applicationQuitOrder = true;
// each step of the closing in the log, to tell from it where a closing that hangs stops
auto const closing{std::chrono::steady_clock::now()};
auto const step = [closing](char const *What) {
WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - closing).count()));
};
// the files found in another case, counted over the whole run: the vehicles, sounds and textures loaded after the scenery
// count as well as those loaded with it
LogFilesInAnotherCase();
step("the sleepers laid in the background");
// the sleepers laid in the background read the scenery, which goes below
track_sleepers::stop_background();
step("the black box");
simulation::Blackbox.close();
step("the physics logs");
// what is kept of them, the black box's written last
PhysicsLogs.stop();
step("the modes");
for (auto &mode : m_modes)
mode.reset();
step("the renderer");
// the screens' post-processing goes with the renderer
m_screenqueue.set_post_processor(nullptr);
GfxRenderer->Shutdown();
m_network.reset();
// SafeDelete( simulation::Train );
step("the odometers");
simulation::Vehicles.save_odometers();
step("the scenery");
SafeDelete(simulation::Region);
step("the ui and the python workers");
ui_layer::shutdown();
// the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed
m_taskqueue.exit();
m_screenqueue.exit();
step("the windows");
for (auto *window : m_windows)
{
glfwDestroyWindow(window);
}
glfwPollEvents(); // TODO: This fixes a segfault on Wayland when closing. Remove after updating glfw to 3.5.
glfwTerminate();
if (!Global.exec_on_exit.empty())
system(Global.exec_on_exit.c_str());
end_timer_period();
step("done");
StopLogService();
auto it = Global.threads.find("LogService");
if (it != Global.threads.end())
{
if (it->second.joinable())
it->second.join();
}
#if WITH_DISCORD_RPC
it = Global.threads.find("DiscordRPC");
if (it != Global.threads.end())
{
if (it->second.joinable())
it->second.join();
}
#endif
}
void eu07_application::render_ui()
{
if (m_crashui)
{
m_crashui();
return;
}
if (m_modestack.empty() || Global.test.enabled)
{
return;
}
m_modes[m_modestack.top()]->render_ui();
}
void eu07_application::begin_ui_frame()
{
// in the test mode nobody sees the window (hidden, the null renderer): no ui frames, whose start polled the window,
// the mouse and the gamepads every frame through imgui's glfw backend
if (m_modestack.empty() || Global.test.enabled)
{
return;
}
m_modes[m_modestack.top()]->begin_ui_frame();
}
bool eu07_application::pop_mode()
{
if (m_modestack.empty())
{
return false;
}
m_modes[m_modestack.top()]->exit();
m_modestack.pop();
return true;
}
bool eu07_application::push_mode(mode const Mode)
{
if (Mode >= count_)
return false;
if (!m_modes[Mode])
{
if (Mode == launcher)
m_modes[Mode] = std::make_shared<launcher_mode>();
if (Mode == scenarioloader)
m_modes[Mode] = std::make_shared<scenarioloader_mode>();
if (Mode == driver)
m_modes[Mode] = std::make_shared<driver_mode>();
if (Mode == editor)
m_modes[Mode] = std::make_shared<editor_mode>();
if (!m_modes[Mode]->init())
return false;
}
m_modes[Mode]->enter();
m_modestack.push(Mode);
return true;
}
void eu07_application::set_title(std::string const &Title)
{
glfwSetWindowTitle(m_windows.front(), Title.c_str());
}
void eu07_application::set_progress(float const Progress, float const Subtaskprogress)
{
if (m_modestack.empty())
{
return;
}
m_modes[m_modestack.top()]->set_progress(Progress, Subtaskprogress);
}
void eu07_application::set_tooltip(std::string const &Tooltip)
{
if (m_modestack.empty())
{
return;
}
m_modes[m_modestack.top()]->set_tooltip(Tooltip);
}
void eu07_application::set_cursor(int const Mode)
{
ui_layer::set_cursor(Mode);
}
void eu07_application::set_cursor_pos(double const Horizontal, double const Vertical)
{
glfwSetCursorPos(m_windows.front(), Horizontal, Vertical);
}
/*
// provides keyboard mapping associated with specified control item
std::string
eu07_application::get_input_hint( user_command const Command ) const {
if( m_modestack.empty() ) { return ""; }
return m_modes[ m_modestack.top() ]->get_input_hint( Command );
}
*/
void eu07_application::on_key(int const Key, int const Scancode, int const Action, int const Mods)
{
if (ui_layer::key_callback(Key, Scancode, Action, Mods))
return;
if (m_modestack.empty())
{
return;
}
#ifdef __unix__
if (Key == GLFW_KEY_LEFT_SHIFT || Key == GLFW_KEY_RIGHT_SHIFT)
Global.shiftState = Action == GLFW_PRESS;
if (Key == GLFW_KEY_LEFT_CONTROL || Key == GLFW_KEY_RIGHT_CONTROL)
Global.ctrlState = Action == GLFW_PRESS;
if (Key == GLFW_KEY_LEFT_ALT || Key == GLFW_KEY_RIGHT_ALT)
Global.altState = Action == GLFW_PRESS;
#endif
m_modes[m_modestack.top()]->on_key(Key, Scancode, Action, Mods);
}
void eu07_application::on_cursor_pos(double const Horizontal, double const Vertical)
{
if (m_modestack.empty())
{
return;
}
m_modes[m_modestack.top()]->on_cursor_pos(Horizontal, Vertical);
}
void eu07_application::on_mouse_button(int const Button, int const Action, int const Mods)
{
if (ui_layer::mouse_button_callback(Button, Action, Mods))
return;
if (m_modestack.empty())
{
return;
}
m_modes[m_modestack.top()]->on_mouse_button(Button, Action, Mods);
}
void eu07_application::on_scroll(double const Xoffset, double const Yoffset)
{
if (ui_layer::scroll_callback(Xoffset, Yoffset))
return;
if (m_modestack.empty())
{
return;
}
m_modes[m_modestack.top()]->on_scroll(Xoffset, Yoffset);
}
void eu07_application::on_char(unsigned int c)
{
if (ui_layer::char_callback(c))
return;
}
void eu07_application::on_focus_change(bool focus)
{
if (Global.bInactivePause && m_network.has_value() && !m_network->client)
{ // jeśli ma być pauzowanie okna w tle
command_relay relay;
relay.post(user_command::focuspauseset, focus ? 1.0 : 0.0, 0.0, GLFW_PRESS, 0);
}
}
void eu07_application::on_window_resize(int w, int h)
{
if (m_modestack.empty())
return;
m_modes[m_modestack.top()]->on_window_resize(w, h);
}
GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int width, int height, GLFWmonitor *monitor, bool keep_ownership, bool share_ctx)
{
if (Windowindex >= 0)
{
return Windowindex < m_windows.size() ? m_windows[Windowindex] : nullptr;
}
// for index -1 create a new child window
auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()};
// a machine without a display (e.g. a test runner) has no monitor to match
if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr})
{
// match requested video mode to current to allow for
// fullwindow creation when resolution is the same
glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
}
glfwWindowHint(GLFW_VISIBLE, visible);
if (share_ctx && (m_gfxbackend != nullptr) && (false == m_gfxbackend->gl_context))
{
// the windows of the renderer have no opengl context to share
WriteLog("window with an opengl context shared with the main window isn't available with the " + m_gfxbackend->name + " renderer");
return nullptr;
}
auto *childwindow = glfwCreateWindow(width, height, "eu07window", monitor, share_ctx ? m_windows.front() : nullptr);
if (!childwindow)
return nullptr;
if (keep_ownership)
m_windows.emplace_back(childwindow);
if (glfwGetWindowAttrib(m_windows.front(), GLFW_VISIBLE))
glfwFocusWindow(m_windows.front()); // restore focus to main window
return childwindow;
}
// private:
GLFWmonitor *eu07_application::find_monitor(const std::string &str) const
{
int monitor_count;
GLFWmonitor **monitors = glfwGetMonitors(&monitor_count);
for (size_t i = 0; i < monitor_count; i++)
{
if (describe_monitor(monitors[i]) == str)
return monitors[i];
}
return nullptr;
}
std::string eu07_application::describe_monitor(GLFWmonitor *monitor) const
{
std::string name(glfwGetMonitorName(monitor));
std::replace(std::begin(name), std::end(name), ' ', '_');
int x, y;
glfwGetMonitorPos(monitor, &x, &y);
return name + ":" + std::to_string(x) + "," + std::to_string(y);
}
// private:
void eu07_application::init_debug()
{
#if defined(_MSC_VER) && defined(_DEBUG)
// memory leaks
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
/*
// floating point operation errors
auto state { _clearfp() };
state = _control87( 0, 0 );
// this will turn on FPE for #IND and zerodiv
state = _control87( state & ~( _EM_ZERODIVIDE | _EM_INVALID ), _MCW_EM );
*/
#endif
}
// Honours Globals.ShowSystemConsole (default: true).
//
// Windows: if the toggle is on, ensure a console is attached (allocate one when
// the binary was linked as the WINDOWS subsystem and none is inherited), then
// reopen the C stdio streams onto it and turn on ENABLE_VIRTUAL_TERMINAL_PROCESSING
// so the ANSI colour escapes used by utilities/Logs.cpp render correctly.
// If the toggle is off, hide the console window (or free an allocated one) so
// the GUI launches without a stray cmd window.
//
// Other platforms: no-op. stdout is the launching terminal (or already detached);
// hiding it on Linux/macOS would mean redirecting to /dev/null and is left to the
// user's shell (e.g. "./eu07 >/dev/null 2>&1").
void eu07_application::init_console()
{
#ifdef _WIN32
if (Global.test.enabled)
{
// a test is started by whoever waits for its result, often reading its output: no console of its own
// (showsystemconsole) pops up and takes stdout away from them, and a console it was started from isn't hidden
return;
}
HWND consoleWnd = ::GetConsoleWindow();
const bool hadConsole = consoleWnd != nullptr;
if (Global.ShowSystemConsole)
{
if (!hadConsole)
{
// no console inherited (e.g. WINDOWS subsystem build, or launched
// detached) -- create one and wire stdio to it so printf in
// utilities/Logs.cpp actually reaches the user
if (::AllocConsole())
{
FILE *fp = nullptr;
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
freopen_s(&fp, "CONIN$", "r", stdin);
// keep C++ streams in sync with the redirected C streams
std::ios::sync_with_stdio(true);
std::cout.clear();
std::cerr.clear();
std::clog.clear();
std::cin.clear();
consoleWnd = ::GetConsoleWindow();
}
}
// enable ANSI virtual-terminal processing so the colour escapes in
// utilities/Logs.cpp ("\033[1;37;41m...", "\033[32m...") render as
// colours instead of literal garbage on the conhost.
//
// IMPORTANT: do NOT rely on GetStdHandle(STD_OUTPUT_HANDLE). After
// AllocConsole + freopen_s the CRT may have rewired things, and on a
// console-subsystem build the std handle can also point to a redirected
// pipe/file rather than the actual console screen buffer -- in either
// case SetConsoleMode silently fails and the escape bytes leak through
// as text ("←[32m" etc). Open CONOUT$ directly to get the real screen
// buffer handle, then flip VT on it.
auto enable_vt = [](const char *devName) {
HANDLE h = ::CreateFileA(
devName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
0,
nullptr);
if (h == INVALID_HANDLE_VALUE)
return;
DWORD mode = 0;
if (::GetConsoleMode(h, &mode))
{
::SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT);
}
::CloseHandle(h);
};
// CONOUT$ is the console's active screen buffer; enabling VT on it
// affects everything that ends up being written there, regardless of
// which FILE* / std handle the writer used
enable_vt("CONOUT$");
if (consoleWnd)
{
::ShowWindow(consoleWnd, SW_SHOW);
// give the console a recognisable title
::SetConsoleTitleA("MaSzyna log");
}
}
else
{
// user wants no console window -- hide whatever we have
if (consoleWnd)
{
::ShowWindow(consoleWnd, SW_HIDE);
}
// if we'd allocated one ourselves on a previous run path we'd FreeConsole here,
// but on first init the console (if any) was inherited from the launcher and
// belongs to it -- just hiding the window is the least-surprising behaviour
}
#endif
}
void eu07_application::init_files()
{
// without multiplelogs the run writes the shared log.txt / errors.txt, and those of the run before go. with it the
// run writes files of its own in logs/, and the shared ones are left to whoever ran the game last without it
for (auto const &file : stale_log_files(Global.MultipleLogs))
{
std::error_code error; // not there is fine
std::filesystem::remove(file, error);
}
#ifdef _WIN32
CreateDirectory("logs", nullptr);
#elif __unix__
mkdir("logs", 0750);
#endif
OpenLogFiles();
}
namespace fs = std::filesystem;
int eu07_application::init_settings(int Argc, char *Argv[])
{
Global.asVersion = VERSION_INFO;
// a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a
// command line it can't take ends with the error code of the test, not with 0, which would pass it
std::vector<char const *> const arguments(Argv, Argv + Argc);
auto const testcommandline{simulation::parse_test_command_line(arguments)};
if (false == testcommandline.error.empty())
{
simulation::test().conclude(simulation::test_result::error, testcommandline.error);
return -1;
}
if (testcommandline.timeout.has_value())
{
Global.test.timeout = *testcommandline.timeout;
Global.test.timeout_from_command_line = true;
}
if (testcommandline.wall_timeout.has_value())
{
Global.test.wall_timeout = testcommandline.wall_timeout;
Global.test.wall_timeout_from_command_line = true;
}
// the simulation snapshots to load and to take (--load-snapshot, --snapshot-at)
auto const snapshotcommandline{simulation::snapshot::parse_command_line(arguments)};
if (false == snapshotcommandline.error.empty())
{
std::cerr << snapshotcommandline.error << std::endl;
simulation::test().conclude(simulation::test_result::error, snapshotcommandline.error);
return -1;
}
fs::path iniPath = user_config_path("eu07.ini");
// a test reads the settings of the game folder only (and those given with -ini), not the player's own
// (%APPDATA%/MaSzyna, ~/.config/MaSzyna), so it runs the same for whoever runs it
if (false == Global.test.enabled && !iniPath.empty() && fs::exists(iniPath))
{
Global.LoadIniFile(iniPath.string().c_str());
}
else
{
Global.LoadIniFile("eu07.ini");
}
if (Global.debug_memorystats)
{
start_heap_counting();
}
// process command line arguments
bool sceneryfromcommandline{false};
bool editwithoutscenery{false};
bool seedfromcommandline{false};
bool vehiclefromcommandline{false};
for (int i = 1; i < Argc; ++i)
{
std::string token{Argv[i]};
if (token == "-s")
{
if (i + 1 < Argc)
{
Global.SceneryFile = ToLower(Argv[++i]);
sceneryfromcommandline = true;
}
}
else if (token == "-v")
{
if (i + 1 < Argc)
{
Global.local_start_vehicle = ToLower(Argv[++i]);
vehiclefromcommandline = true;
}
}
else if (token == "-edit")
{
// edit session: the scenery is loaded without player vehicle, straight into the editor
Global.editor_session = true;
Global.local_start_vehicle = "ghostview";
if (i + 1 < Argc && Argv[i + 1][0] != '-')
{
Global.SceneryFile = ToLower(Argv[++i]);
sceneryfromcommandline = true;
}
else
editwithoutscenery = true;
}
else if (token == "-seed")
{
// a number is the seed; anything else is a word that stands for one. said in the
// log as it was given, because that is what gets passed on to somebody else. 0 is a seed
// too; an empty word gives none, as randomseed with nothing after it
if (i + 1 < Argc)
{
if (auto const seed{seed_given(Argv[++i])})
{
Global.random_seed = *seed;
Global.random_seed_given = true;
seedfromcommandline = true;
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
}
}
}
else if (token == "--test")
{
// integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541),
// taken from the command line above
}
else if (token == "--test-timeout" || token == "--test-wall-timeout")
{
// taken from the command line above, with its value
++i;
}
else if (token == "--load-snapshot" || token == "--snapshot-at" || token == "--load-snapshot-force")
{
// taken from the command line above, with their values
i += simulation::snapshot::option_value_count(token);
}
else if (token == "-ini")
{
// extra settings file read on top of eu07.ini, so a run can override a few keys
// (window size, physicslog...) without touching the user's own config
if (i + 1 < Argc)
{
Global.LoadIniFile(Argv[++i]);
}
}
else
{
// a test's standard output carries its result only
(Global.test.enabled ? std::cerr : std::cout) << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
<< " [-v vehiclename]"
<< " [-edit [sceneryfilepath]]"
<< " [-seed number|word]"
<< " [-ini settingsfile]"
<< " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]"
<< " [--load-snapshot file [--load-snapshot-force]] [--snapshot-at seconds file]" << std::endl;
simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token));
return -1;
}
}
if (editwithoutscenery && false == sceneryfromcommandline)
Global.SceneryFile.clear();
simulation::snapshot::request(snapshotcommandline);
// the scenery of a snapshot loads the way it did when the snapshot was taken only with the seed it had then
if (auto const seed{simulation::snapshot::requested_seed()}; seed.has_value() && false == seedfromcommandline)
{
Global.random_seed = *seed;
Global.random_seed_given = true;
WriteLog(std::format("seed taken from the snapshot to load: {}", Global.random_seed));
}
// and the player goes on in the vehicle they were in
if (auto const vehicle{simulation::snapshot::requested_player_vehicle()}; false == vehicle.empty() && false == vehiclefromcommandline)
Global.local_start_vehicle = vehicle;
if (Global.test.enabled)
{
if (false == sceneryfromcommandline || Global.SceneryFile.empty())
{
simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s");
return -1;
}
simulation::apply_test_mode_settings();
}
// a renderer this build doesn't have: the values of the removed renderers are taken for "default" as eu07.ini is read
// (global_settings::ConfigParse), and a vulkan renderer which can't run here falls back to opengl (select_gfx_backend())
return 0;
}
int eu07_application::init_locale()
{
Translations.init();
return 0;
}
int eu07_application::init_glfw()
{
// set before glfwInit(), so a failure of the start itself is told too
glfwSetErrorCallback(glfw_error_callback);
if (glfwInit() == GLFW_FALSE)
{
ErrorLog("Bad init: failed to initialize glfw");
return -1;
}
{
int monitor_count;
GLFWmonitor **monitors = glfwGetMonitors(&monitor_count);
WriteLog("available monitors:");
for (size_t i = 0; i < monitor_count; i++)
{
WriteLog(describe_monitor(monitors[i]));
}
}
select_gfx_backend();
return create_main_window();
}
void eu07_application::select_gfx_backend()
{
auto *factory{gfx_renderer_factory::get_instance()};
m_gfxbackend = nullptr;
if (Global.GfxRenderer == "vulkan")
{
// a renderer which can't run here falls back to opengl, so a setting in eu07.ini doesn't leave the user with a black screen
std::string reason;
auto const *vulkan{factory->backend("vulkan")};
if (vulkan == nullptr)
{
reason = "this build of the simulator has no vulkan renderer";
}
else if ((vulkan->probe == nullptr) || vulkan->probe(reason))
{
m_gfxbackend = vulkan;
}
if (m_gfxbackend == nullptr)
{
WriteLog("gfxrenderer vulkan: not available (" + reason + "), using opengl");
crashreport_add_info("gfxrenderer_fallback", reason);
Global.GfxRenderer = "default";
}
}
else if (Global.GfxRenderer == "null")
{
// draws nothing and loads no textures (test mode)
m_gfxbackend = factory->backend("null");
}
if (m_gfxbackend == nullptr)
{
m_gfxbackend = factory->backend("modern");
}
crashreport_add_info("gfxrenderer", Global.GfxRenderer);
WriteLog("renderer: " + (m_gfxbackend != nullptr ? m_gfxbackend->name : std::string("none")));
}
int eu07_application::create_main_window()
{
if (m_gfxbackend == nullptr)
{
ErrorLog("Bad init: no renderer found");
return -1;
}
auto *monitor{find_monitor(Global.fullscreen_monitor)};
if (!monitor)
monitor = glfwGetPrimaryMonitor();
// the window may be made a second time, after another backend was tried
glfwDefaultWindowHints();
glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE);
// NOTE: the hints stay in effect for the additional windows and shared contexts created later through window()
if (m_gfxbackend->window_hints != nullptr)
m_gfxbackend->window_hints();
if (Global.fullscreen_windowed)
{
auto const mode = glfwGetVideoMode(monitor);
Global.window_size.x = mode->width;
Global.window_size.y = mode->height;
Global.bFullScreen = true;
}
// test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it.
// so does a selftest of the editor run while the computer is in use for something else: never shown nor focused
bool const shown{false == Global.test.enabled && selftest_script("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr};
auto *mainwindow = window(-1, shown, Global.window_size.x, Global.window_size.y, Global.bFullScreen && shown ? monitor : nullptr, true, false);
if (mainwindow == nullptr)
{
char const *glfwerror = nullptr;
glfwGetError(&glfwerror);
std::string const reason = (glfwerror != nullptr ? glfwerror : "unknown error");
if (m_gfxbackend->window_failed != nullptr)
m_gfxbackend->window_failed(reason);
ErrorLog("Bad init: failed to create glfw window");
return -1;
}
if ((m_gfxbackend->after_window != nullptr) && (false == m_gfxbackend->after_window(mainwindow)))
{
return -1;
}
{
int width, height;
glfwGetFramebufferSize(mainwindow, &width, &height);
framebuffer_resize_callback(mainwindow, width, height);
glfwGetWindowSize(mainwindow, &width, &height);
window_resize_callback(mainwindow, width, height);
}
#ifdef _WIN32
// setup wrapper for base glfw window proc, to handle copydata messages
Hwnd = glfwGetWin32Window(mainwindow);
// commands sent by other programs are input from outside, which a test doesn't take
if (false == Global.test.enabled)
BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
// switch off the topmost flag
::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
#endif
return 0;
}
int eu07_application::fallback_to_opengl(std::string const &Reason)
{
WriteLog("gfxrenderer vulkan: " + Reason + ", using opengl");
crashreport_add_info("gfxrenderer_fallback", Reason);
Global.GfxRenderer = "default";
m_gfxbackend = gfx_renderer_factory::get_instance()->backend("modern");
crashreport_add_info("gfxrenderer", Global.GfxRenderer);
WriteLog("renderer: " + (m_gfxbackend != nullptr ? m_gfxbackend->name : std::string("none")));
// nothing hangs on the window yet (the ui is set up later), so it can be made anew with the hints of opengl
for (auto *window : m_windows)
glfwDestroyWindow(window);
m_windows.clear();
return create_main_window();
}
void eu07_application::init_callbacks()
{
auto *window{m_windows.front()};
glfwSetWindowSizeCallback(window, window_resize_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);
glfwSetWindowFocusCallback(window, focus_callback);
glfwSetCursorEnterCallback(window, cursor_enter_callback);
if (Global.test.enabled)
{
// a test takes no input: keys and clicks sent to its hidden window would change the run
return;
}
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetCharCallback(window, char_callback);
}
int eu07_application::init_ui()
{
if (false == ui_layer::init(m_windows.front()))
{
return -1;
}
init_callbacks();
return 0;
}
int eu07_application::init_gfx()
{
// NOTE: global_settings maps unsupported gfxrenderer values (e.g. the removed "legacy") to "default"
GfxRenderer = (m_gfxbackend != nullptr && m_gfxbackend->create != nullptr) ? m_gfxbackend->create() : nullptr;
if (!GfxRenderer)
{
ErrorLog("no renderer found!");
return -1;
}
if (false == GfxRenderer->Init(m_windows.front()))
{
if (Global.GfxRenderer != "vulkan")
{
return -1;
}
// the reason is in the log already
GfxRenderer->Shutdown();
GfxRenderer.reset();
if (fallback_to_opengl("the renderer failed to start") != 0)
{
return -1;
}
GfxRenderer = m_gfxbackend->create();
if (!GfxRenderer || (false == GfxRenderer->Init(m_windows.front())))
{
return -1;
}
}
for (const global_settings::extraviewport_config &conf : Global.extra_viewports)
if (!GfxRenderer->AddViewport(conf))
return -1;
if (!Global.headtrack_conf.joy.empty())
m_headtrack.emplace();
return 0;
}
int eu07_application::init_audio()
{
if (Global.bSoundEnabled)
{
Global.bSoundEnabled &= audio::renderer.init();
}
// NOTE: lack of audio isn't deemed a failure serious enough to throw in the towel
return 0;
}
int eu07_application::init_data()
{
// HACK: grab content of the first {} block in load_unit_weights using temporary parser, then parse it normally. on any error our weight list will be empty string
auto loadweights{cParser(cParser("data/load_weights.txt", cParser::buffer_FILE).getToken<std::string>(true, "{}"), cParser::buffer_TEXT)};
while (true == loadweights.getTokens(2))
{
std::pair<std::string, float> weightpair;
loadweights >> weightpair.first >> weightpair.second;
weightpair.first.erase(weightpair.first.end() - 1); // trim trailing ':' from the key
simulation::Weights.emplace(weightpair.first, weightpair.second);
}
cParser override_parser("data/sound_overrides.txt", cParser::buffer_FILE);
deserialize_map(simulation::Sound_overrides, override_parser);
return 0;
}
int eu07_application::init_modes()
{
// local cosmetics only (sound pitch, editor placement), never security related
Global.local_random_engine.seed(static_cast<std::mt19937::result_type>(true_random_seed())); // NOSONAR
if ((!Global.network_servers.empty() || Global.network_client) && Global.SceneryFile.empty())
{
ErrorLog("launcher mode is currently not supported in network mode");
return -1;
}
// activate the default mode
if (Global.SceneryFile.empty())
push_mode(mode::launcher);
else
push_mode(mode::scenarioloader);
return 0;
}
bool eu07_application::init_network()
{
if (!Global.network_servers.empty() || Global.network_client)
{
// create network manager
m_network.emplace();
}
for (auto const &pair : Global.network_servers)
{
// create all servers
m_network->create_server(pair.first, pair.second);
}
if (Global.network_client)
{
// create client
m_network->connect(Global.network_client->first, Global.network_client->second);
}
else
{
// we're simulation master
// TODO: sort out this timezone mess
std::time_t utc_now = std::time(nullptr);
std::tm const tm_local = local_tm(utc_now);
std::tm const tm_utc = utc_tm(utc_now);
int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec);
Global.starting_timestamp = utc_now + offset;
Global.ready_to_load = true;
}
return true;
}