Conversion to cpp 20

This commit is contained in:
2026-01-18 21:21:15 +01:00
parent ecf5934209
commit 11e79f52ae
10 changed files with 1014 additions and 908 deletions

View File

@@ -33,7 +33,7 @@ set(VERSION_PATCH ${VERSION_DAY})
set(VERSION_STRING "${VERSION_YEAR}.${VERSION_MONTH}.${VERSION_DAY}")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD 20)
file(GLOB HEADERS "*.h"
"Console/*.h"

View File

@@ -77,10 +77,8 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo)
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
int main(int argc, char *argv[])
{
#ifdef WITHDUMPGEN
@@ -92,22 +90,37 @@ int main(int argc, char *argv[])
Global.startTimestamp = std::chrono::steady_clock::now();
// quick short-circuit for standalone e3d export
if (argc == 6 && std::string(argv[1]) == "-e3d") {
if (argc == 6 && std::string(argv[1]) == "-e3d")
{
std::string in(argv[2]);
std::string out(argv[3]);
int flags = std::stoi(std::string(argv[4]));
int dynamic = std::stoi(std::string(argv[5]));
export_e3d_standalone(in, out, flags, dynamic);
} else {
try {
}
else
{
try
{
auto result{Application.init(argc, argv)};
if( result == 0 ) {
if (result == 0)
{
result = Application.run();
Application.exit();
}
} catch( std::bad_alloc const &Error ) {
}
catch (std::bad_alloc const &Error)
{
ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what()));
}
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
std::string msg = "Simulator crash occured :(\n";
msg += Error.what();
MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
}
#endif
}
#ifndef _WIN32
fflush(stdout);

257
PyInt.cpp
View File

@@ -20,22 +20,45 @@ http://mozilla.org/MPL/2.0/.
#endif
#include <simulation.h>
void render_task::run() {
void render_task::run()
{
// convert provided input to a python dictionary
auto *input = PyDict_New();
if (input == nullptr) {
if (input == nullptr)
{
cancel();
return;
}
for( auto const &datapair : m_input->floats ) { auto *value{ PyGetFloat( datapair.second ) }; PyDict_SetItemString( input, datapair.first.c_str(), value ); Py_DECREF( value ); }
for( auto const &datapair : m_input->integers ) { auto *value{ PyGetInt( datapair.second ) }; PyDict_SetItemString( input, datapair.first.c_str(), value ); Py_DECREF( value ); }
for( auto const &datapair : m_input->bools ) { auto *value{ PyGetBool( datapair.second ) }; PyDict_SetItemString( input, datapair.first.c_str(), value ); }
for( auto const &datapair : m_input->strings ) { auto *value{ PyGetString( datapair.second.c_str() ) }; PyDict_SetItemString( input, datapair.first.c_str(), value ); Py_DECREF( value ); }
for (auto const &datapair : m_input->vec2_lists) {
for (auto const &datapair : m_input->floats)
{
auto *value{PyGetFloat(datapair.second)};
PyDict_SetItemString(input, datapair.first.c_str(), value);
Py_DECREF(value);
}
for (auto const &datapair : m_input->integers)
{
auto *value{PyGetInt(datapair.second)};
PyDict_SetItemString(input, datapair.first.c_str(), value);
Py_DECREF(value);
}
for (auto const &datapair : m_input->bools)
{
auto *value{PyGetBool(datapair.second)};
PyDict_SetItemString(input, datapair.first.c_str(), value);
}
for (auto const &datapair : m_input->strings)
{
auto *value{PyGetString(datapair.second.c_str())};
PyDict_SetItemString(input, datapair.first.c_str(), value);
Py_DECREF(value);
}
for (auto const &datapair : m_input->vec2_lists)
{
PyObject *list = PyList_New(datapair.second.size());
for (size_t i = 0; i < datapair.second.size(); i++) {
for (size_t i = 0; i < datapair.second.size(); i++)
{
auto const &vec = datapair.second[i];
WriteLog("passing " + glm::to_string(vec));
@@ -52,16 +75,16 @@ void render_task::run() {
m_input = nullptr;
// call the renderer
auto *output { PyObject_CallMethod( m_renderer, "render", "O", input ) };
auto *output{PyObject_CallMethod(m_renderer, const_cast<char *>("render"), const_cast<char *>("O"), input)};
Py_DECREF(input);
if( output != nullptr ) {
auto *outputwidth { PyObject_CallMethod( m_renderer, "get_width", nullptr ) };
auto *outputheight { PyObject_CallMethod( m_renderer, "get_height", nullptr ) };
if (output != nullptr)
{
auto *outputwidth{PyObject_CallMethod(m_renderer, const_cast<char *>("get_width"), nullptr)};
auto *outputheight{PyObject_CallMethod(m_renderer, const_cast<char *>("get_height"), nullptr)};
// upload texture data
if( ( outputwidth != nullptr )
&& ( outputheight != nullptr )
&& m_target) {
if ((outputwidth != nullptr) && (outputheight != nullptr) && m_target)
{
int width = PyInt_AsLong(outputwidth);
int height = PyInt_AsLong(outputheight);
int components, format;
@@ -102,13 +125,19 @@ void render_task::run() {
m_target->format = format;
m_target->timestamp = std::chrono::high_resolution_clock::now();
}
if( outputheight != nullptr ) { Py_DECREF( outputheight ); }
if( outputwidth != nullptr ) { Py_DECREF( outputwidth ); }
if (outputheight != nullptr)
{
Py_DECREF(outputheight);
}
if (outputwidth != nullptr)
{
Py_DECREF(outputwidth);
}
Py_DECREF(output);
}
// get commands from renderer
auto *commandsPO = PyObject_CallMethod(m_renderer, "getCommands", nullptr);
auto *commandsPO = PyObject_CallMethod(m_renderer, const_cast<char *>("getCommands"), nullptr);
if (commandsPO != nullptr)
{
std::vector<std::string> commands = python_external_utils::PyObjectToStringArray(commandsPO);
@@ -152,7 +181,8 @@ void render_task::run() {
cd.param1 = p1;
cd.param2 = p2;
WriteLog("Python: Executing command [" + baseCmd + "] with params: P1=" + std::to_string(p1) + " P2=" + std::to_string(p2) + " Target ID=" + std::to_string(simulation::Train->id()));
WriteLog("Python: Executing command [" + baseCmd + "] with params: P1=" + std::to_string(p1) + " P2=" + std::to_string(p2) +
" Target ID=" + std::to_string(simulation::Train->id()));
simulation::Commands.push(cd, static_cast<size_t>(command_target::vehicle) | simulation::Train->id());
}
@@ -162,13 +192,7 @@ void render_task::run() {
}
}
}
}
}
void render_task::upload()
@@ -198,31 +222,30 @@ void render_task::upload()
}
}
void render_task::cancel() {
}
void render_task::cancel() {}
// initializes the module. returns true on success
auto python_taskqueue::init() -> bool {
auto python_taskqueue::init() -> bool
{
crashreport_add_info("python.threadedupload", Global.python_threadedupload ? "yes" : "no");
crashreport_add_info("python.uploadmain", Global.python_uploadmain ? "yes" : "no");
#ifdef _WIN32
if (sizeof(void *) == 8)
Py_SetPythonHome("python64");
Py_SetPythonHome(const_cast<char *>("python64"));
else
Py_SetPythonHome("python");
Py_SetPythonHome(const_cast<char *>("python"));
#elif __linux__
if (sizeof(void *) == 8)
Py_SetPythonHome("linuxpython64");
Py_SetPythonHome(const_cast<char *>("linuxpython64"));
else
Py_SetPythonHome("linuxpython");
Py_SetPythonHome(const_cast<char *>("linuxpython"));
#elif __APPLE__
if (sizeof(void *) == 8)
Py_SetPythonHome("macpython64");
Py_SetPythonHome(const_cast<char *>("macpython64"));
else
Py_SetPythonHome("macpython");
Py_SetPythonHome(const_cast<char *>("macpython"));
#endif
Py_InitializeEx(0);
@@ -234,26 +257,21 @@ auto python_taskqueue::init() -> bool {
// do the setup work while we hold the lock
m_main = PyImport_ImportModule("__main__");
if (m_main == nullptr) {
if (m_main == nullptr)
{
ErrorLog("Python Interpreter: __main__ module is missing");
goto release_and_exit;
}
stringiomodule = PyImport_ImportModule("cStringIO");
stringioclassname = (
stringiomodule != nullptr ?
PyObject_GetAttrString( stringiomodule, "StringIO" ) :
nullptr );
stringioobject = (
stringioclassname != nullptr ?
PyObject_CallObject( stringioclassname, nullptr ) :
nullptr );
m_stderr = { (
stringioobject == nullptr ? nullptr :
PySys_SetObject( "stderr", stringioobject ) != 0 ? nullptr :
stringioobject ) };
stringioclassname = (stringiomodule != nullptr ? PyObject_GetAttrString(stringiomodule, "StringIO") : nullptr);
stringioobject = (stringioclassname != nullptr ? PyObject_CallObject(stringioclassname, nullptr) : nullptr);
m_stderr = {(stringioobject == nullptr ? nullptr : PySys_SetObject(const_cast<char *>("stderr"), stringioobject) != 0 ? nullptr : stringioobject)};
if( false == run_file( "abstractscreenrenderer" ) ) { goto release_and_exit; }
if (false == run_file("abstractscreenrenderer"))
{
goto release_and_exit;
}
// release the lock, save the state for future use
m_mainthread = PyEval_SaveThread();
@@ -261,16 +279,18 @@ auto python_taskqueue::init() -> bool {
WriteLog("Python Interpreter: setup complete");
// init workers
for( auto &worker : m_workers ) {
for (auto &worker : m_workers)
{
GLFWwindow *openglcontextwindow = nullptr;
if (Global.python_threadedupload)
openglcontextwindow = Application.window(-1);
worker = std::thread(
&python_taskqueue::run, this,
openglcontextwindow, std::ref( m_tasks ), std::ref(m_uploadtasks), std::ref( m_condition ), std::ref( m_exit ) );
worker = std::jthread(&python_taskqueue::run, this, openglcontextwindow, std::ref(m_tasks), std::ref(m_uploadtasks), std::ref(m_condition), std::ref(m_exit));
if( false == worker.joinable() ) { return false; }
if (false == worker.joinable())
{
return false;
}
}
m_initialized = true;
@@ -283,7 +303,8 @@ release_and_exit:
}
// shuts down the module
void python_taskqueue::exit() {
void python_taskqueue::exit()
{
if (!m_initialized)
return;
@@ -291,13 +312,11 @@ void python_taskqueue::exit() {
m_exit = true;
m_condition.notify_all();
// let them free up their shit before we proceed
for( auto &worker : m_workers ) {
if (worker.joinable())
worker.join();
}
m_workers = {};
// get rid of the leftover tasks
// with the workers dead we don't have to worry about concurrent access anymore
for( auto task : m_tasks.data ) {
for (auto task : m_tasks.data)
{
task->cancel();
}
// take a bow
@@ -306,16 +325,19 @@ void python_taskqueue::exit() {
}
// adds specified task along with provided collection of data to the work queue. returns true on success
auto python_taskqueue::insert( task_request const &Task ) -> bool {
auto python_taskqueue::insert(task_request const &Task) -> bool
{
if( !m_initialized
|| ( false == Global.python_enabled )
|| ( Task.renderer.empty() )
|| ( Task.input == nullptr )
|| ( Task.target == 0 ) ) { return false; }
if (!m_initialized || (false == Global.python_enabled) || (Task.renderer.empty()) || (Task.input == nullptr) || (Task.target == 0))
{
return false;
}
auto *renderer{fetch_renderer(Task.renderer)};
if( renderer == nullptr ) { return false; }
if (renderer == nullptr)
{
return false;
}
auto newtask = std::make_shared<render_task>(renderer, Task.input, Task.target);
bool newtaskinserted{false};
@@ -323,8 +345,10 @@ auto python_taskqueue::insert( task_request const &Task ) -> bool {
{
std::lock_guard<std::mutex> lock(m_tasks.mutex);
// check the task list for a pending request with the same target
for( auto &task : m_tasks.data ) {
if( task->target() == Task.target ) {
for (auto &task : m_tasks.data)
{
if (task->target() == Task.target)
{
// replace pending task in the slot with the more recent one
task->cancel();
task = newtask;
@@ -332,7 +356,8 @@ auto python_taskqueue::insert( task_request const &Task ) -> bool {
break;
}
}
if( false == newtaskinserted ) {
if (false == newtaskinserted)
{
m_tasks.data.emplace_back(newtask);
}
}
@@ -343,16 +368,21 @@ auto python_taskqueue::insert( task_request const &Task ) -> bool {
}
// executes python script stored in specified file. returns true on success
auto python_taskqueue::run_file( std::string const &File, std::string const &Path ) -> bool {
auto python_taskqueue::run_file(std::string const &File, std::string const &Path) -> bool
{
auto const lookup{FileExists({Path + File, "python/local/" + File}, {".py"})};
if( lookup.first.empty() ) { return false; }
if (lookup.first.empty())
{
return false;
}
std::ifstream inputfile{lookup.first + lookup.second};
std::string input;
input.assign(std::istreambuf_iterator<char>(inputfile), std::istreambuf_iterator<char>());
if( PyRun_SimpleString( input.c_str() ) != 0 ) {
if (PyRun_SimpleString(input.c_str()) != 0)
{
error();
return false;
}
@@ -361,21 +391,25 @@ auto python_taskqueue::run_file( std::string const &File, std::string const &Pat
}
// acquires the python gil and sets the main thread as current
void python_taskqueue::acquire_lock() {
void python_taskqueue::acquire_lock()
{
PyEval_RestoreThread(m_mainthread);
}
// releases the python gil and swaps the main thread out
void python_taskqueue::release_lock() {
void python_taskqueue::release_lock()
{
PyEval_SaveThread();
}
auto python_taskqueue::fetch_renderer( std::string const Renderer ) ->PyObject * {
auto python_taskqueue::fetch_renderer(std::string const Renderer) -> PyObject *
{
auto const lookup{m_renderers.find(Renderer)};
if( lookup != std::end( m_renderers ) ) {
if (lookup != std::end(m_renderers))
{
return lookup->second;
}
// try to load specified renderer class
@@ -386,36 +420,42 @@ auto python_taskqueue::fetch_renderer( std::string const Renderer ) ->PyObject *
PyObject *renderername{nullptr};
acquire_lock();
{
if( m_main == nullptr ) {
if (m_main == nullptr)
{
ErrorLog("Python Renderer: __main__ module is missing");
goto cache_and_return;
}
if( false == run_file( file, path ) ) {
if (false == run_file(file, path))
{
goto cache_and_return;
}
renderername = PyObject_GetAttrString(m_main, file.c_str());
if( renderername == nullptr ) {
if (renderername == nullptr)
{
ErrorLog("Python Renderer: class \"" + file + "\" not defined");
goto cache_and_return;
}
rendererarguments = Py_BuildValue("(s)", path.c_str());
if( rendererarguments == nullptr ) {
if (rendererarguments == nullptr)
{
ErrorLog("Python Renderer: failed to create initialization arguments");
goto cache_and_return;
}
renderer = PyObject_CallObject(renderername, rendererarguments);
PyObject_CallMethod(renderer, "manul_set_format", "(s)", "RGBA");
PyObject_CallMethod(renderer, const_cast<char *>("manul_set_format"), const_cast<char *>("(s)"), "RGBA");
if( PyErr_Occurred() != nullptr ) {
if (PyErr_Occurred() != nullptr)
{
error();
renderer = nullptr;
}
cache_and_return:
// clean up after yourself
if( rendererarguments != nullptr ) {
if (rendererarguments != nullptr)
{
Py_DECREF(rendererarguments);
}
}
@@ -425,7 +465,8 @@ cache_and_return:
return renderer;
}
void python_taskqueue::run( GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic<bool> &Exit ) {
void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uploadtask_sequence &Upload_Tasks, threading::condition_variable &Condition, std::atomic<bool> &Exit)
{
if (Context)
glfwMakeContextCurrent(Context);
@@ -437,22 +478,26 @@ void python_taskqueue::run( GLFWwindow *Context, rendertask_sequence &Tasks, upl
std::shared_ptr<render_task> task{nullptr};
while( false == Exit.load() ) {
while (false == Exit.load())
{
// regardless of the reason we woke up prime the spurious wakeup flag for the next time
Condition.spurious(true);
// keep working as long as there's any scheduled tasks
do {
do
{
task = nullptr;
// acquire a lock on the task queue and potentially grab a task from it
{
std::lock_guard<std::mutex> lock(Tasks.mutex);
if( false == Tasks.data.empty() ) {
if (false == Tasks.data.empty())
{
// fifo
task = Tasks.data.front();
Tasks.data.pop_front();
}
}
if( task != nullptr ) {
if (task != nullptr)
{
// swap in my thread state
PyEval_RestoreThread(threadstate);
{
@@ -495,46 +540,53 @@ void python_taskqueue::update()
m_uploadtasks.data.clear();
}
void
python_taskqueue::error() {
void python_taskqueue::error()
{
if( m_stderr != nullptr ) {
if (m_stderr != nullptr)
{
// std err pythona jest buforowane
PyErr_Print();
auto *errortext { PyObject_CallMethod( m_stderr, "getvalue", nullptr ) };
auto *errortext{PyObject_CallMethod(m_stderr, const_cast<char *>("getvalue"), nullptr)};
ErrorLog(PyString_AsString(errortext));
// czyscimy bufor na kolejne bledy
PyObject_CallMethod( m_stderr, "truncate", "i", 0 );
PyObject_CallMethod(m_stderr, const_cast<char *>("truncate"), const_cast<char *>("i"), 0);
}
else {
else
{
// nie dziala buffor pythona
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
if( type == nullptr ) {
if (type == nullptr)
{
ErrorLog("Python Interpreter: don't know how to handle null exception");
}
PyErr_NormalizeException(&type, &value, &traceback);
if( type == nullptr ) {
if (type == nullptr)
{
ErrorLog("Python Interpreter: don't know how to handle null exception");
}
auto *typetext{PyObject_Str(type)};
if( typetext != nullptr ) {
if (typetext != nullptr)
{
ErrorLog(PyString_AsString(typetext));
}
if( value != nullptr ) {
if (value != nullptr)
{
ErrorLog(PyString_AsString(value));
}
auto *tracebacktext{PyObject_Str(traceback)};
if( tracebacktext != nullptr ) {
if (tracebacktext != nullptr)
{
ErrorLog(PyString_AsString(tracebacktext));
}
else {
else
{
WriteLog("Python Interpreter: failed to retrieve the stack traceback");
}
}
}
std::vector<std::string> python_external_utils::PyObjectToStringArray(PyObject *pyList)
{
std::vector<std::string> result;
@@ -570,7 +622,6 @@ std::vector<std::string> python_external_utils::PyObjectToStringArray(PyObject *
return result;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

25
PyInt.h
View File

@@ -50,6 +50,7 @@ http://mozilla.org/MPL/2.0/.
#include "Classes.h"
#include "utilities.h"
#include "Texture.h"
#include <thread>
#define PyGetFloat(param) PyFloat_FromDouble(param)
#define PyGetInt(param) PyInt_FromLong(param)
@@ -57,7 +58,8 @@ http://mozilla.org/MPL/2.0/.
#define PyGetString(param) PyString_FromString(param)
// python rendertarget
struct python_rt {
struct python_rt
{
std::mutex mutex;
ITexture *shared_tex;
@@ -72,18 +74,20 @@ struct python_rt {
};
// TODO: extract common base and inherit specialization from it
class render_task {
class render_task
{
public:
// constructors
render_task( PyObject *Renderer, std::shared_ptr<dictionary_source> Input, std::shared_ptr<python_rt> Target ) :
m_renderer( Renderer ), m_input( Input ), m_target( Target )
{}
render_task(PyObject *Renderer, std::shared_ptr<dictionary_source> Input, std::shared_ptr<python_rt> Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {}
// methods
void run();
void upload();
void cancel();
auto target() const -> std::shared_ptr<python_rt> { return m_target; }
auto target() const -> std::shared_ptr<python_rt>
{
return m_target;
}
private:
// members
@@ -92,11 +96,13 @@ private:
std::shared_ptr<python_rt> m_target{nullptr};
};
class python_taskqueue {
class python_taskqueue
{
public:
// types
struct task_request {
struct task_request
{
std::string const &renderer;
std::shared_ptr<dictionary_source> input;
@@ -123,7 +129,7 @@ public:
private:
// types
static int const WORKERCOUNT{1};
using worker_array = std::array<std::thread, WORKERCOUNT >;
using worker_array = std::array<std::jthread, WORKERCOUNT>;
using rendertask_sequence = threading::lockable<std::deque<std::shared_ptr<render_task>>>;
using uploadtask_sequence = threading::lockable<std::deque<std::shared_ptr<render_task>>>;
// methods
@@ -148,7 +154,6 @@ class python_external_utils
{
public:
static std::vector<std::string> PyObjectToStringArray(PyObject *pyList);
};
#endif

View File

@@ -135,24 +135,24 @@ int eu07_application::run_crashgui()
if (Global.asLang == "pl")
{
ImGui::Begin(u8"Raportowanie błędów", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize);
ImGui::TextUnformatted(u8"Podczas ostatniego uruchomienia symulatora wystąpił błąd.\nWysłać raport o błędzie do deweloperów?\n");
ImGui::TextUnformatted((u8"Usługa udostępniana przez " + crashreport_get_provider() + "\n").c_str());
y = ImGui::Button(u8"Tak", ImVec2S(60, 0));
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(u8"W przyszłości przesyłaj raporty o błędach automatycznie", &autoup);
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(u8"W celu wyłączenia tej funkcji będzie trzeba skasować plik crashdumps/autoupload_enabled.conf");
ImGui::TextUnformatted("W celu wyłączenia tej funkcji będzie trzeba skasować plik crashdumps/autoupload_enabled.conf");
ImGui::EndTooltip();
}
ImGui::NewLine();
n = ImGui::Button(u8"Nie", ImVec2S(60, 0));
n = ImGui::Button("Nie", ImVec2S(60, 0));
ImGui::End();
}
else

View File

@@ -391,7 +391,7 @@ timetable_panel::update() {
}
else {
// header
m_tablelines.emplace_back( u8"┌─────┬────────────────────────────────────┬─────────┬─────┐", Global.UITextColor );
m_tablelines.emplace_back( "┌─────┬────────────────────────────────────┬─────────┬─────┐", Global.UITextColor );
TMTableLine const *tableline;
for( int i = table.StationStart; i <= table.StationCount; ++i ) {
@@ -423,11 +423,11 @@ timetable_panel::update() {
auto const arrival { (
tableline->Ah >= 0 ?
to_string( int( 100 + tableline->Ah ) ).substr( 1, 2 ) + ":" + to_minutes_str( tableline->Am, true, 3 ) :
u8"" ) };
"" ) };
auto const departure { (
tableline->Dh >= 0 ?
to_string( int( 100 + tableline->Dh ) ).substr( 1, 2 ) + ":" + to_minutes_str( tableline->Dm, true, 3 ) :
u8"" ) };
"" ) };
auto const candepart { (
( table.StationStart < table.StationIndex )
&& ( i < table.StationIndex )
@@ -446,25 +446,25 @@ timetable_panel::update() {
candepart ? colors::uitextgreen : // czas minął i odjazd był, to nazwa stacji będzie na zielono
isatpassengerstop ? colors::uitextorange :
Global.UITextColor ) };
auto const trackcount{ ( tableline->TrackNo == 1 ? u8"" : u8"" ) };
auto const trackcount{ ( tableline->TrackNo == 1 ? "" : "" ) };
m_tablelines.emplace_back(
( u8"" + vmax + u8"" + station + trackcount + arrival + u8"" + traveltime + u8"" ),
( "" + vmax + "" + station + trackcount + arrival + "" + traveltime + "" ),
linecolor );
m_tablelines.emplace_back(
( u8"│ │ " + location + tableline->StationWare + trackcount + departure + u8" │ │" ),
( "│ │ " + location + tableline->StationWare + trackcount + departure + " │ │" ),
linecolor );
// divider/footer
if( i < table.StationCount ) {
auto const *nexttableline { tableline + 1 };
std::string const vmaxnext{ ( tableline->vmax == nexttableline->vmax ? u8"│ ├" : u8"├─────┼" ) };
auto const trackcountnext{ ( nexttableline->TrackNo == 1 ? u8"" : u8"" ) };
std::string const vmaxnext{ ( tableline->vmax == nexttableline->vmax ? "│ ├" : "├─────┼" ) };
auto const trackcountnext{ ( nexttableline->TrackNo == 1 ? "" : "" ) };
m_tablelines.emplace_back(
vmaxnext + u8"────────────────────────────────────" + trackcountnext + u8"─────────┼─────┤",
vmaxnext + "────────────────────────────────────" + trackcountnext + "─────────┼─────┤",
Global.UITextColor );
}
else {
m_tablelines.emplace_back(
u8"└─────┴────────────────────────────────────┴─────────┴─────┘",
"└─────┴────────────────────────────────────┴─────────┴─────┘",
Global.UITextColor );
}
}

View File

@@ -24,80 +24,87 @@ http://mozilla.org/MPL/2.0/.
// cParser -- generic class for parsing text data.
// constructors
cParser::cParser( std::string const &Stream, buffertype const Type, std::string Path, bool const Loadtraction, std::vector<std::string> Parameters, bool allowRandom ) :
mPath(Path),
LoadTraction( Loadtraction ),
allowRandomIncludes(allowRandom) {
cParser::cParser(std::string const &Stream, buffertype const Type, std::string Path, bool const Loadtraction, std::vector<std::string> Parameters, bool allowRandom)
: mPath(Path), LoadTraction(Loadtraction), allowRandomIncludes(allowRandom)
{
// store to calculate sub-sequent includes from relative path
if( Type == buffertype::buffer_FILE ) {
if (Type == buffertype::buffer_FILE)
{
mFile = Stream;
}
// reset pointers and attach proper type of buffer
switch (Type) {
case buffer_FILE: {
switch (Type)
{
case buffer_FILE:
{
Path.append(Stream);
mStream = std::make_shared<std::ifstream>(Path, std::ios_base::binary);
// content of *.inc files is potentially grouped together
if( ( Stream.size() >= 4 )
&& ( ToLower( Stream.substr( Stream.size() - 4 ) ) == ".inc" ) ) {
if ((Stream.size() >= 4) && (ToLower(Stream.substr(Stream.size() - 4)) == ".inc"))
{
mIncFile = true;
scene::Groups.create();
}
break;
}
case buffer_TEXT: {
case buffer_TEXT:
{
mStream = std::make_shared<std::istringstream>(Stream);
break;
}
default: {
default:
{
break;
}
}
// calculate stream size
if (mStream)
{
if( true == mStream->fail() ) {
if (true == mStream->fail())
{
ErrorLog("Failed to open file \"" + Path + "\"");
}
else {
else
{
mSize = mStream->rdbuf()->pubseekoff(0, std::ios_base::end);
mStream->rdbuf()->pubseekoff(0, std::ios_base::beg);
mLine = 1;
}
}
// set parameter set if one was provided
if( false == Parameters.empty() ) {
if (false == Parameters.empty())
{
parameters.swap(Parameters);
}
}
// destructor
cParser::~cParser() {
cParser::~cParser()
{
if( true == mIncFile ) {
if (true == mIncFile)
{
// wrap up the node group holding content of processed file
scene::Groups.close();
}
}
template <>
glm::vec3
cParser::getToken( bool const ToLower, char const *Break ) {
template <> glm::vec3 cParser::getToken(bool const ToLower, char const *Break)
{
// NOTE: this specialization ignores default arguments
getTokens(3, false, "\n\r\t ,;[]");
glm::vec3 output;
*this
>> output.x
>> output.y
>> output.z;
*this >> output.x >> output.y >> output.z;
return output;
};
template<>
cParser&
cParser::operator>>( std::string &Right ) {
template <> cParser &cParser::operator>>(std::string &Right)
{
if( true == this->tokens.empty() ) { return *this; }
if (true == this->tokens.empty())
{
return *this;
}
Right = this->tokens.front();
this->tokens.pop_front();
@@ -105,43 +112,44 @@ cParser::operator>>( std::string &Right ) {
return *this;
}
template<>
cParser&
cParser::operator>>( bool &Right ) {
template <> cParser &cParser::operator>>(bool &Right)
{
if( true == this->tokens.empty() ) { return *this; }
if (true == this->tokens.empty())
{
return *this;
}
Right = ( ( this->tokens.front() == "true" )
|| ( this->tokens.front() == "yes" )
|| ( this->tokens.front() == "1" ) );
Right = ((this->tokens.front() == "true") || (this->tokens.front() == "yes") || (this->tokens.front() == "1"));
this->tokens.pop_front();
return *this;
}
template <>
bool
cParser::getToken<bool>( bool const ToLower, const char *Break ) {
template <> bool cParser::getToken<bool>(bool const ToLower, const char *Break)
{
auto const token = getToken<std::string>(true, Break);
return ( ( token == "true" )
|| ( token == "yes" )
|| ( token == "1" ) );
return ((token == "true") || (token == "yes") || (token == "1"));
}
// methods
cParser &
cParser::autoclear( bool const Autoclear ) {
cParser &cParser::autoclear(bool const Autoclear)
{
m_autoclear = Autoclear;
if( mIncludeParser ) { mIncludeParser->autoclear( Autoclear ); }
if (mIncludeParser)
{
mIncludeParser->autoclear(Autoclear);
}
return *this;
}
bool cParser::getTokens(unsigned int Count, bool ToLower, const char *Break)
{
if( true == m_autoclear ) {
if (true == m_autoclear)
{
// legacy parser behaviour
tokens.clear();
}
@@ -159,7 +167,8 @@ bool cParser::getTokens(unsigned int Count, bool ToLower, const char *Break)
for (unsigned int i = tokens.size(); i < Count; ++i)
{
std::string token = readToken(ToLower, Break);
if( true == token.empty() ) {
if (true == token.empty())
{
// no more tokens
break;
}
@@ -183,21 +192,27 @@ bool cParser::getTokens(unsigned int Count, bool ToLower, const char *Break)
return true;
}
std::string cParser::readToken( bool ToLower, const char *Break ) {
std::string cParser::readToken(bool ToLower, const char *Break)
{
std::string token;
if( mIncludeParser ) {
if (mIncludeParser)
{
// see if there's include parsing going on. clean up when it's done.
token = mIncludeParser->readToken(ToLower, Break);
if( true == token.empty() ) {
if (true == token.empty())
{
mIncludeParser = nullptr;
}
}
if( true == token.empty() ) {
if (true == token.empty())
{
// get the token yourself if the delegation attempt failed
char c{0};
do {
while( mStream->peek() != EOF && strchr( Break, c = mStream->get() ) == NULL ) {
do
{
while (mStream->peek() != EOF && strchr(Break, c = mStream->get()) == NULL)
{
if (ToLower)
c = tolower(c);
token += c;
@@ -206,33 +221,40 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
if (skipComments && trimComments(token)) // don't glue together words separated with comment
break;
}
if( c == '\n' ) {
if (c == '\n')
{
// update line counter
++mLine;
}
} while (token == "" && mStream->peek() != EOF); // double check in case of consecutive separators
}
// check the first token for potential presence of utf bom
if( mFirstToken ) {
if (mFirstToken)
{
mFirstToken = false;
if( token.rfind( "\xef\xbb\xbf", 0 ) == 0 ) {
if (token.rfind("\xef\xbb\xbf", 0) == 0)
{
token.erase(0, 3);
}
if( true == token.empty() ) {
if (true == token.empty())
{
// potentially possible if our first token was standalone utf bom
token = readToken(ToLower, Break);
}
}
if( false == parameters.empty() ) {
if (false == parameters.empty())
{
// if there's parameter list, check the token for potential parameters to replace
size_t pos; // początek podmienianego ciągu
while( ( pos = token.find( "(p" ) ) != std::string::npos ) {
while ((pos = token.find("(p")) != std::string::npos)
{
// check if the token is a parameter which should be replaced with stored true value
auto const parameter{token.substr(pos + 2, token.find(")", pos) - (pos + 2))}; // numer parametru
token.erase(pos, token.find(")", pos) - pos + 1); // najpierw usunięcie "(pN)"
size_t nr = atoi(parameter.c_str()) - 1;
if( nr < parameters.size() ) {
if (nr < parameters.size())
{
token.insert(pos, parameters.at(nr)); // wklejenie wartości parametru
if (ToLower)
for (; pos < parameters.at(nr).size(); ++pos)
@@ -245,21 +267,23 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
// launch child parser if include directive found.
// NOTE: parameter collecting uses default set of token separators.
if( expandIncludes && token == "include" ) {
if (expandIncludes && token == "include")
{
std::string includefile = allowRandomIncludes ? deserialize_random_set(*this) : readToken(ToLower); // nazwa pliku
replace_slashes(includefile);
if ((true == LoadTraction) ||
((false == contains(includefile, "tr/")) && (false == contains(includefile, "tra/"))))
if ((true == LoadTraction) || ((false == contains(includefile, "tr/")) && (false == contains(includefile, "tra/"))))
{
if (false == contains(includefile, "_ter.scm"))
{
if (Global.ParserLogIncludes) {
if (Global.ParserLogIncludes)
{
// WriteLog("including: " + includefile);
}
mIncludeParser = std::make_shared<cParser>(includefile, buffer_FILE, mPath, LoadTraction, readParameters(*this));
mIncludeParser->allowRandomIncludes = allowRandomIncludes;
mIncludeParser->autoclear(m_autoclear);
if (mIncludeParser->mSize <= 0) {
if (mIncludeParser->mSize <= 0)
{
ErrorLog("Bad include: can't open file \"" + includefile + "\"");
}
}
@@ -272,11 +296,11 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
}
else
{
if (Global.ParserLogIncludes) {
if (Global.ParserLogIncludes)
{
WriteLog("including terrain: " + includefile);
}
mIncludeParser = std::make_shared<cParser>(includefile, buffer_FILE, mPath,
LoadTraction, readParameters(*this));
mIncludeParser = std::make_shared<cParser>(includefile, buffer_FILE, mPath, LoadTraction, readParameters(*this));
mIncludeParser->allowRandomIncludes = allowRandomIncludes;
mIncludeParser->autoclear(m_autoclear);
if (mIncludeParser->mSize <= 0)
@@ -286,28 +310,30 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
}
}
}
else {
while( token != "end" ) {
else
{
while (token != "end")
{
token = readToken(true); // minimize risk of case mismatch on comparison
}
}
token = readToken(ToLower, Break);
}
else if( ( std::strcmp( Break, "\n\r" ) == 0 ) && ( token.compare( 0, 7, "include" ) == 0 ) ) {
else if ((std::strcmp(Break, "\n\r") == 0) && (token.compare(0, 7, "include") == 0))
{
// HACK: if the parser reads full lines we expect this line to contain entire include directive, to make parsing easier
cParser includeparser(token.substr(7));
std::string includefile = allowRandomIncludes ? deserialize_random_set(includeparser) : includeparser.readToken(ToLower); // nazwa pliku
replace_slashes(includefile);
if ((true == LoadTraction) ||
((false == contains(includefile, "tr/")) && (false == contains(includefile, "tra/"))))
if ((true == LoadTraction) || ((false == contains(includefile, "tr/")) && (false == contains(includefile, "tra/"))))
{
if (false == contains(includefile, "_ter.scm"))
{
if (Global.ParserLogIncludes) {
if (Global.ParserLogIncludes)
{
// WriteLog("including: " + includefile);
}
mIncludeParser = std::make_shared<cParser>(
includefile, buffer_FILE, mPath, LoadTraction, readParameters(includeparser));
mIncludeParser = std::make_shared<cParser>(includefile, buffer_FILE, mPath, LoadTraction, readParameters(includeparser));
mIncludeParser->allowRandomIncludes = allowRandomIncludes;
mIncludeParser->autoclear(m_autoclear);
if (mIncludeParser->mSize <= 0)
@@ -324,19 +350,17 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
}
else
{
if (Global.ParserLogIncludes) {
if (Global.ParserLogIncludes)
{
WriteLog("including terrain: " + includefile);
}
mIncludeParser =
std::make_shared<cParser>(includefile, buffer_FILE, mPath, LoadTraction,
readParameters(includeparser));
mIncludeParser = std::make_shared<cParser>(includefile, buffer_FILE, mPath, LoadTraction, readParameters(includeparser));
mIncludeParser->allowRandomIncludes = allowRandomIncludes;
mIncludeParser->autoclear(m_autoclear);
if (mIncludeParser->mSize <= 0)
{
ErrorLog("Bad include: can't open file \"" + includefile + "\"");
}
}
}
}
@@ -346,30 +370,36 @@ std::string cParser::readToken( bool ToLower, const char *Break ) {
return token;
}
std::vector<std::string> cParser::readParameters( cParser &Input ) {
std::vector<std::string> cParser::readParameters(cParser &Input)
{
std::vector<std::string> includeparameters;
std::string parameter = Input.readToken(false); // w parametrach nie zmniejszamy
while( ( parameter.empty() == false )
&& ( parameter != "end" ) ) {
while ((parameter.empty() == false) && (parameter != "end"))
{
includeparameters.emplace_back(parameter);
parameter = Input.readToken(false);
}
return includeparameters;
}
std::string cParser::readQuotes(char const Quote) { // read the stream until specified char or stream end
std::string cParser::readQuotes(char const Quote)
{ // read the stream until specified char or stream end
std::string token = "";
char c{0};
bool escaped = false;
while( mStream->peek() != EOF ) { // get all chars until the quote mark
while (mStream->peek() != EOF)
{ // get all chars until the quote mark
c = mStream->get();
if (escaped) {
if (escaped)
{
escaped = false;
}
else {
if (c == '\\') {
else
{
if (c == '\\')
{
escaped = true;
continue;
}
@@ -385,21 +415,25 @@ std::string cParser::readQuotes(char const Quote) { // read the stream until spe
return token;
}
void cParser::skipComment( std::string const &Endmark ) { // pobieranie znaków aż do znalezienia znacznika końca
void cParser::skipComment(std::string const &Endmark)
{ // pobieranie znaków aż do znalezienia znacznika końca
std::string input = "";
char c{0};
auto const endmarksize = Endmark.size();
while( mStream->peek() != EOF ) {
while (mStream->peek() != EOF)
{
// o ile nie koniec pliku
c = mStream->get(); // pobranie znaku
if( c == '\n' ) {
if (c == '\n')
{
// update line counter
++mLine;
}
input += c;
if (input == Endmark) // szukanie znacznika końca
break;
if( input.size() >= endmarksize ) {
if (input.size() >= endmarksize)
{
// keep the read text short, to avoid pointless string re-allocations on longer comments
input = input.substr(1);
}
@@ -407,9 +441,11 @@ void cParser::skipComment( std::string const &Endmark ) { // pobieranie znaków
return;
}
bool cParser::findQuotes( std::string &String ) {
bool cParser::findQuotes(std::string &String)
{
if( String.back() == '\"' ) {
if (String.back() == '\"')
{
String.pop_back();
String += readQuotes();
@@ -422,7 +458,10 @@ bool cParser::trimComments(std::string &String)
{
for (auto const &comment : mComments)
{
if( String.size() < comment.first.size() ) { continue; }
if (String.size() < comment.first.size())
{
continue;
}
if (String.compare(String.size() - comment.first.size(), comment.first.size(), comment.first) == 0)
{
@@ -436,10 +475,12 @@ bool cParser::trimComments(std::string &String)
void cParser::injectString(const std::string &str)
{
if (mIncludeParser) {
if (mIncludeParser)
{
mIncludeParser->injectString(str);
}
else {
else
{
mIncludeParser = std::make_shared<cParser>(str, buffer_TEXT, "", LoadTraction, std::vector<std::string>(), allowRandomIncludes);
mIncludeParser->autoclear(m_autoclear);
}
@@ -450,23 +491,29 @@ int cParser::getProgress() const
return static_cast<int>(mStream->rdbuf()->pubseekoff(0, std::ios_base::cur) * 100 / mSize);
}
int cParser::getFullProgress() const {
int cParser::getFullProgress() const
{
int progress = getProgress();
if( mIncludeParser ) return progress + ( ( 100 - progress )*( mIncludeParser->getProgress() ) / 100 );
else return progress;
if (mIncludeParser)
return progress + ((100 - progress) * (mIncludeParser->getProgress()) / 100);
else
return progress;
}
std::size_t cParser::countTokens( std::string const &Stream, std::string Path ) {
std::size_t cParser::countTokens(std::string const &Stream, std::string Path)
{
return cParser(Stream, buffer_FILE, Path).count();
}
std::size_t cParser::count() {
std::size_t cParser::count()
{
std::string token;
size_t count{0};
do {
do
{
token = "";
token = readToken(false);
++count;
@@ -475,27 +522,41 @@ std::size_t cParser::count() {
return count - 1;
}
void cParser::addCommentStyle( std::string const &Commentstart, std::string const &Commentend ) {
void cParser::addCommentStyle(std::string const &Commentstart, std::string const &Commentend)
{
mComments.insert(commentmap::value_type(Commentstart, Commentend));
}
// returns name of currently open file, or empty string for text type stream
std::string
cParser::Name() const {
std::string cParser::Name() const
{
if( mIncludeParser ) { return mIncludeParser->Name(); }
else { return mPath + mFile; }
if (mIncludeParser)
{
return mIncludeParser->Name();
}
else
{
return mPath + mFile;
}
}
// returns number of currently processed line
std::size_t
cParser::Line() const {
std::size_t cParser::Line() const
{
if( mIncludeParser ) { return mIncludeParser->Line(); }
else { return mLine; }
if (mIncludeParser)
{
return mIncludeParser->Line();
}
else
{
return mLine;
}
}
int cParser::LineMain() const {
int cParser::LineMain() const
{
return mIncludeParser ? -1 : mLine;
}

View File

@@ -322,7 +322,7 @@ bool string_starts_with(const std::string &string, const std::string &begin)
return string.compare(0, begin.length(), begin) == 0;
}
std::string const fractionlabels[] = {" ", u8"¹", u8"²", u8"³", u8"", u8"", u8"", u8"", u8"", u8""};
std::string const fractionlabels[] = {" ", "¹", "²", "³", "", "", "", "", "", ""};
std::string to_minutes_str(float const Minutes, bool const Leadingzero, int const Width)
{
@@ -376,8 +376,8 @@ void win1250_to_ascii(std::string &Input)
std::string win1250_to_utf8(const std::string &Input)
{
std::unordered_map<char, std::string> const charmap{{165, u8"Ą"}, {198, u8"Ć"}, {202, u8"Ę"}, {163, u8"Ł"}, {209, u8"Ń"}, {211, u8"Ó"}, {140, u8"Ś"}, {143, u8"Ź"}, {175, u8"Ż"},
{185, u8"ą"}, {230, u8"ć"}, {234, u8"ę"}, {179, u8"ł"}, {241, u8"ń"}, {243, u8"ó"}, {156, u8"ś"}, {159, u8"ź"}, {191, u8"ż"}};
std::unordered_map<char, std::string> const charmap{{165, "Ą"}, {198, "Ć"}, {202, "Ę"}, {163, "Ł"}, {209, "Ń"}, {211, "Ó"}, {140, "Ś"}, {143, "Ź"}, {175, "Ż"},
{185, "ą"}, {230, "ć"}, {234, "ę"}, {179, "ł"}, {241, "ń"}, {243, "ó"}, {156, "ś"}, {159, "ź"}, {191, "ż"}};
std::string output;
std::unordered_map<char, std::string>::const_iterator lookup;
for (auto &input : Input)

View File

@@ -7,8 +7,7 @@
#include <sys/stat.h>
#endif
trainingcard_panel::trainingcard_panel()
: ui_panel("Raport szkolenia", false)
trainingcard_panel::trainingcard_panel() : ui_panel("Raport szkolenia", false)
{
// size = {400, 500};
clear();
@@ -58,9 +57,11 @@ void trainingcard_panel::save_thread_func()
std::fstream input("report_template.html", std::ios_base::in | std::ios_base::binary);
std::string in_line;
while (std::getline(input, in_line)) {
while (std::getline(input, in_line))
{
const std::string magic("{{CONTENT}}");
if (in_line.compare(0, magic.size(), magic) == 0) {
if (in_line.compare(0, magic.size(), magic) == 0)
{
temp << "<div><b>Miejsce: </b>" << (std::string(place.c_str())) << "</div><br />" << std::endl;
temp << "<div><b>Data: </b>" << (date) << "</div><br />" << std::endl;
temp << "<div><b>Czas: </b>" << (from) << " - " << (to) << "</div><br />" << std::endl;
@@ -72,7 +73,9 @@ void trainingcard_panel::save_thread_func()
if (distance > 0.0f)
temp << "<div><b>Przebyta odległość: </b>" << std::round(distance) << " km</div><br />" << std::endl;
temp << "<div><b>Uwagi: </b><br />" << (remarks) << "</div>" << std::endl;
} else {
}
else
{
temp << in_line;
}
}
@@ -85,37 +88,42 @@ void trainingcard_panel::save_thread_func()
void trainingcard_panel::render_contents()
{
if (ImGui::BeginPopupModal("Zapisywanie danych")) {
if (ImGui::BeginPopupModal("Zapisywanie danych"))
{
ImGui::SetWindowSize(ImVec2(-1, -1));
int s = state.load();
if (s == 1) {
if (s == 1)
{
ImGui::CloseCurrentPopup();
clear();
}
if (s < 1) {
if (s < 1)
{
if (s == 0)
ImGui::TextUnformatted("Error occured please contact with administrator!");
if (s == -1)
ImGui::TextUnformatted("The recording of the training has not been archived, please do not start the next training before manually archiving the file!");
if (ImGui::Button("OK")) {
if (ImGui::Button("OK"))
{
ImGui::CloseCurrentPopup();
clear();
}
}
if (s == 2)
ImGui::TextUnformatted(u8"Proszę czekać, trwa archiwizacja nagrania...");
ImGui::TextUnformatted("Proszę czekać, trwa archiwizacja nagrania...");
ImGui::EndPopup();
}
if (start_time_wall) {
if (start_time_wall)
{
std::tm *tm = std::localtime(&(*start_time_wall));
std::string rep = u8"Czas rozpoczęcia: " + std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday)
+ " " + std::to_string(tm->tm_hour) + ":" + std::to_string(tm->tm_min);
std::string rep = "Czas rozpoczęcia: " + std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday) + " " + std::to_string(tm->tm_hour) +
":" + std::to_string(tm->tm_min);
ImGui::TextUnformatted(rep.c_str());
}
@@ -146,22 +154,27 @@ void trainingcard_panel::render_contents()
ImGui::TextUnformatted("Uwagi");
ImGui::InputTextMultiline("##remarks", &remarks[0], remarks.size(), ImVec2(-1.0f, 200.0f));
if (!start_time_wall) {
if (ImGui::Button("Rozpocznij szkolenie")) {
if (!start_time_wall)
{
if (ImGui::Button("Rozpocznij szkolenie"))
{
start_time_wall = std::time(nullptr);
std::tm *tm = std::localtime(&(*start_time_wall));
recording_timestamp = std::to_string(tm->tm_year + 1900) + std::to_string(tm->tm_mon + 1) + std::to_string(tm->tm_mday)
+ std::to_string(tm->tm_hour) + std::to_string(tm->tm_min) + "_" + std::string(trainee_name.c_str()) + "_" + std::string(instructor_name.c_str());
recording_timestamp = std::to_string(tm->tm_year + 1900) + std::to_string(tm->tm_mon + 1) + std::to_string(tm->tm_mday) + std::to_string(tm->tm_hour) + std::to_string(tm->tm_min) + "_" +
std::string(trainee_name.c_str()) + "_" + std::string(instructor_name.c_str());
int ret = StartRecording();
if (ret != 1) {
if (ret != 1)
{
state.store(ret);
ImGui::OpenPopup("Zapisywanie danych");
}
}
}
else {
if (ImGui::Button(u8"Zakończ szkolenie")) {
else
{
if (ImGui::Button("Zakończ szkolenie"))
{
state.store(2);
if (simulation::Trains.sequence().size() > 0)
distance = simulation::Trains.sequence()[0]->Dynamic()->MoverParameters->DistCounter;

View File

@@ -5,27 +5,26 @@
#include "Driver.h"
#include "Train.h"
ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle)
: ui_panel(std::string(STR("Vehicle parameters")) + ": " + vehicle, false), m_vehicle_name(vehicle)
ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle) : ui_panel(std::string(STR("Vehicle parameters")) + ": " + vehicle, false), m_vehicle_name(vehicle)
{
vehicle_mini = GfxRenderer->Fetch_Texture("vehicle_mini");
}
void screen_window_callback(ImGuiSizeCallbackData *data) {
void screen_window_callback(ImGuiSizeCallbackData *data)
{
auto config = static_cast<const global_settings::pythonviewport_config *>(data->UserData);
data->DesiredSize.y = data->DesiredSize.x * (float)config->size.y / (float)config->size.x;
}
void ui::vehicleparams_panel::draw_infobutton(const char *str, ImVec2 pos, const ImVec4 color)
{
if (pos.x != -1.0f) {
if (pos.x != -1.0f)
{
ImVec2 window_size = ImGui::GetWindowSize();
ImGuiStyle &style = ImGui::GetStyle();
ImVec2 text_size = ImGui::CalcTextSize(str);
ImVec2 button_size = ImVec2(
text_size.x + style.FramePadding.x * 2.0f,
text_size.y + style.FramePadding.y * 2.0f);
ImVec2 button_size = ImVec2(text_size.x + style.FramePadding.x * 2.0f, text_size.y + style.FramePadding.y * 2.0f);
pos.x = pos.x * window_size.x / 512.0f - button_size.x / 2.0f;
pos.y = pos.y * window_size.y / 118.0f - button_size.y / 2.0f;
@@ -64,9 +63,9 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover)
ImGui::Image(reinterpret_cast<void *>(tex.get_id()), ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0));
if (mover.Pantographs[end::rear].is_active)
draw_infobutton(u8"╨╨╨", ImVec2(126, 10));
draw_infobutton("╨╨╨", ImVec2(126, 10));
if (mover.Pantographs[end::front].is_active)
draw_infobutton(u8"╨╨╨", ImVec2(290, 10));
draw_infobutton("╨╨╨", ImVec2(290, 10));
if (mover.Battery)
draw_infobutton(STR_C("bat."), ImVec2(120, 55));
@@ -99,24 +98,28 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover)
void ui::vehicleparams_panel::render_contents()
{
TDynamicObject *vehicle_ptr = simulation::Vehicles.find(m_vehicle_name);
if (!vehicle_ptr) {
if (!vehicle_ptr)
{
is_open = false;
return;
}
TTrain *train_ptr = simulation::Trains.find(m_vehicle_name);
if (train_ptr) {
if (train_ptr)
{
const TTrain::screenentry_sequence &screens = train_ptr->get_screens();
for (const auto &viewport : Global.python_viewports) {
for (auto const &entry : screens) {
for (const auto &viewport : Global.python_viewports)
{
for (auto const &entry : screens)
{
if (entry.script != viewport.surface)
continue;
std::string window_name = STR("Screen") + "##" + viewport.surface;
ImGui::SetNextWindowSizeConstraints(ImVec2(200, 200), ImVec2(2500, 2500), screen_window_callback,
const_cast<global_settings::pythonviewport_config*>(&viewport));
if (ImGui::Begin(window_name.c_str())) {
ImGui::SetNextWindowSizeConstraints(ImVec2(200, 200), ImVec2(2500, 2500), screen_window_callback, const_cast<global_settings::pythonviewport_config *>(&viewport));
if (ImGui::Begin(window_name.c_str()))
{
float aspect = (float)viewport.size.y / viewport.size.x;
glm::mat3 proj = glm::translate(glm::scale(glm::mat3(), 1.0f / viewport.scale), viewport.offset);
@@ -142,160 +145,118 @@ void ui::vehicleparams_panel::render_contents()
auto const isdieselenginepowered{(mover.EngineType == TEngineType::DieselElectric) || (mover.EngineType == TEngineType::DieselEngine)};
auto const isdieselinshuntmode{mover.ShuntMode && mover.EngineType == TEngineType::DieselElectric};
std::snprintf(
buffer.data(), buffer.size(),
STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"),
std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"),
// devices
( mover.Battery ? 'B' : '.' ),
( mover.Mains ? 'M' : '.' ),
( mover.FuseFlag ? '!' : '.' ),
( mover.Pantographs[end::rear].is_active ? ( mover.PantRearVolt > 0.0 ? 'O' : 'o' ) : '.' ),
( mover.Pantographs[end::front].is_active ? ( mover.PantFrontVolt > 0.0 ? 'P' : 'p' ) : '.' ),
( mover.PantPressLockActive ? '!' : ( mover.PantPressSwitchActive ? '*' : '.' ) ),
(mover.Battery ? 'B' : '.'), (mover.Mains ? 'M' : '.'), (mover.FuseFlag ? '!' : '.'), (mover.Pantographs[end::rear].is_active ? (mover.PantRearVolt > 0.0 ? 'O' : 'o') : '.'),
(mover.Pantographs[end::front].is_active ? (mover.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (mover.PantPressLockActive ? '!' : (mover.PantPressSwitchActive ? '*' : '.')),
(mover.WaterPump.is_active ? 'W' : (false == mover.WaterPump.breaker ? '-' : (mover.WaterPump.is_enabled ? 'w' : '.'))),
(true == mover.WaterHeater.is_damaged ? '!' : (mover.WaterHeater.is_active ? 'H' : (false == mover.WaterHeater.breaker ? '-' : (mover.WaterHeater.is_enabled ? 'h' : '.')))),
( mover.FuelPump.is_active ? 'F' : ( mover.FuelPump.is_enabled ? 'f' : '.' ) ),
( mover.OilPump.is_active ? 'O' : ( mover.OilPump.is_enabled ? 'o' : '.' ) ),
( false == mover.ConverterAllowLocal ? '-' : ( mover.ConverterAllow ? ( mover.ConverterFlag ? 'X' : 'x' ) : '.' ) ),
( mover.ConvOvldFlag ? '!' : '.' ),
(mover.FuelPump.is_active ? 'F' : (mover.FuelPump.is_enabled ? 'f' : '.')), (mover.OilPump.is_active ? 'O' : (mover.OilPump.is_enabled ? 'o' : '.')),
(false == mover.ConverterAllowLocal ? '-' : (mover.ConverterAllow ? (mover.ConverterFlag ? 'X' : 'x') : '.')), (mover.ConvOvldFlag ? '!' : '.'),
(mover.CompressorFlag ? 'C' : (false == mover.CompressorAllowLocal ? '-' : ((mover.CompressorAllow || mover.CompressorStart == start_t::automatic) ? 'c' : '.'))),
( mover.CompressorGovernorLock ? '!' : '.' ),
"",
std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( mover.OilPump.pressure, 2 ) : "" ).c_str(),
(mover.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(mover.OilPump.pressure, 2) : "").c_str(),
// power transfers
mover.Couplers[ end::front ].power_high.voltage,
mover.Couplers[ end::front ].power_high.current,
std::string( mover.Couplers[ end::front ].power_high.is_local ? "" : "-" ).c_str(),
std::string( vehicle.DirectionGet() ? ":<<:" : ":>>:" ).c_str(),
std::string( mover.Couplers[ end::rear ].power_high.is_local ? "" : "-" ).c_str(),
mover.Couplers[ end::rear ].power_high.voltage,
mover.Couplers[ end::rear ].power_high.current );
mover.Couplers[end::front].power_high.voltage, mover.Couplers[end::front].power_high.current, std::string(mover.Couplers[end::front].power_high.is_local ? "" : "-").c_str(),
std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(mover.Couplers[end::rear].power_high.is_local ? "" : "-").c_str(),
mover.Couplers[end::rear].power_high.voltage, mover.Couplers[end::rear].power_high.current);
ImGui::TextUnformatted(buffer.data());
std::snprintf(
buffer.data(), buffer.size(),
STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, cooling fans: %.0f+%.0f"),
std::snprintf(buffer.data(), buffer.size(),
STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, "
"cooling fans: %.0f+%.0f"),
// controllers
mover.MainCtrlPos,
mover.MainCtrlActualPos,
mover.MainCtrlPos, mover.MainCtrlActualPos,
std::string(isdieselinshuntmode ? to_string(mover.AnPos, 2) + STR(" (shunt mode)") : std::to_string(mover.ScndCtrlPos) + "(" + std::to_string(mover.ScndCtrlActualPos) + ")").c_str(),
// engine
mover.EnginePower,
std::abs( mover.TrainType == dt_EZT ? mover.ShowCurrent( 0 ) : mover.Im ),
mover.EnginePower, std::abs(mover.TrainType == dt_EZT ? mover.ShowCurrent(0) : mover.Im),
// revolutions
std::abs( mover.enrot ) * 60,
std::abs( mover.nrot ) * mover.Transmision.Ratio * 60,
mover.RventRot * 60,
std::abs( mover.MotorBlowers[end::front].revolutions ),
std::abs( mover.MotorBlowers[end::rear].revolutions ),
mover.dizel_heat.rpmw,
mover.dizel_heat.rpmw2 );
std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[end::front].revolutions),
std::abs(mover.MotorBlowers[end::rear].revolutions), mover.dizel_heat.rpmw, mover.dizel_heat.rpmw2);
ImGui::TextUnformatted(buffer.data());
if( isdieselenginepowered ) {
std::snprintf(
buffer.data(), buffer.size(),
STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"),
mover.dizel_heat.Ts,
mover.dizel_heat.To,
mover.dizel_heat.temperatura1,
( mover.WaterCircuitsLink ? '-' : '|' ),
mover.dizel_heat.temperatura2 );
if (isdieselenginepowered)
{
std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), mover.dizel_heat.Ts, mover.dizel_heat.To, mover.dizel_heat.temperatura1,
(mover.WaterCircuitsLink ? '-' : '|'), mover.dizel_heat.temperatura2);
ImGui::TextUnformatted(buffer.data());
}
std::string brakedelay;
{
std::vector<std::pair<int, std::string>> delays {
{ bdelay_G, "G" },
{ bdelay_P, "P" },
{ bdelay_R, "R" },
{ bdelay_M, "+Mg" } };
std::vector<std::pair<int, std::string>> delays{{bdelay_G, "G"}, {bdelay_P, "P"}, {bdelay_R, "R"}, {bdelay_M, "+Mg"}};
for( auto const &delay : delays ) {
if( ( mover.BrakeDelayFlag & delay.first ) == delay.first ) {
for (auto const &delay : delays)
{
if ((mover.BrakeDelayFlag & delay.first) == delay.first)
{
brakedelay += delay.second;
}
}
}
std::snprintf(
buffer.data(), buffer.size(),
STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"),
std::snprintf(buffer.data(), buffer.size(),
STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n "
"brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"),
// brakes
mover.fBrakeCtrlPos,
mover.LocalBrakePosA,
mover.BrakeOpModeFlag,
brakedelay.c_str(),
mover.LoadFlag,
mover.fBrakeCtrlPos, mover.LocalBrakePosA, mover.BrakeOpModeFlag, brakedelay.c_str(), mover.LoadFlag,
// cylinders
mover.BrakePress,
mover.LocBrakePress,
mover.Hamulec->GetBrakeStatus(),
mover.BrakePress, mover.LocBrakePress, mover.Hamulec->GetBrakeStatus(),
// pipes
mover.PipePress,
mover.BrakeCtrlPos2,
mover.ScndPipePress,
mover.CntrlPipePress,
mover.PipePress, mover.BrakeCtrlPos2, mover.ScndPipePress, mover.CntrlPipePress,
// tanks
mover.Hamulec->GetBRP(),
mover.Compressor,
mover.Hamulec->GetCRP() );
mover.Hamulec->GetBRP(), mover.Compressor, mover.Hamulec->GetCRP());
ImGui::TextUnformatted(buffer.data());
if( mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) {
std::snprintf(
buffer.data(), buffer.size(),
STR_C(" pantograph: %.2f%cMT"),
mover.PantPress,
( mover.bPantKurek3 ? '-' : '|' ) );
if (mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector)
{
std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), mover.PantPress, (mover.bPantKurek3 ? '-' : '|'));
ImGui::TextUnformatted(buffer.data());
}
std::snprintf(
buffer.data(), buffer.size(),
STR_C("Forces:\n tractive: %.1f, brake: %.1f, friction: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"),
std::snprintf(buffer.data(), buffer.size(),
STR_C("Forces:\n tractive: %.1f, brake: %.1f, friction: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: "
"[%.2f, %.2f, %.2f]"),
// forces
mover.Ft * 0.001f * ( mover.CabActive ? mover.CabActive : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive : 1 ) + 0.001f,
mover.Fb * 0.001f,
mover.Adhesive( mover.RunningTrack.friction ),
( mover.SlippingWheels ? " (!)" : "" ),
mover.Ft * 0.001f *
(mover.CabActive ? mover.CabActive :
vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive :
1) +
0.001f,
mover.Fb * 0.001f, mover.Adhesive(mover.RunningTrack.friction), (mover.SlippingWheels ? " (!)" : ""),
// acceleration
mover.AccSVBased,
mover.AccN + 0.001f,
std::string( std::abs( mover.RunningShape.R ) > 10000.0 ? "~0" : to_string( mover.RunningShape.R, 0 ) ).c_str(),
mover.AccSVBased, mover.AccN + 0.001f, std::string(std::abs(mover.RunningShape.R) > 10000.0 ? "~0" : to_string(mover.RunningShape.R, 0)).c_str(),
// velocity
vehicle.GetVelocity(),
mover.DistCounter,
vehicle.GetVelocity(), mover.DistCounter,
// position
vehicle.GetPosition().x,
vehicle.GetPosition().y,
vehicle.GetPosition().z );
vehicle.GetPosition().x, vehicle.GetPosition().y, vehicle.GetPosition().z);
ImGui::TextUnformatted(buffer.data());
std::pair<double, double> TrainsetPowerMeter;
TDynamicObject *vehicle_iter = vehicle_ptr;
while (vehicle_iter) {
while (vehicle_iter)
{
if (vehicle_iter->Next())
vehicle_iter = vehicle_iter->Next();
else
break;
}
while (vehicle_iter) {
while (vehicle_iter)
{
TrainsetPowerMeter.first += vehicle_iter->MoverParameters->EnergyMeter.first;
TrainsetPowerMeter.second += vehicle_iter->MoverParameters->EnergyMeter.second;
vehicle_iter = vehicle_iter->Prev();
}
if (TrainsetPowerMeter.first != 0.0 || TrainsetPowerMeter.second != 0.0) {
std::snprintf(buffer.data(), buffer.size(), STR_C("Electricity usage:\n drawn: %.1f kWh\n returned: %.1f kWh\n balance: %.1f kWh"),
TrainsetPowerMeter.first, -TrainsetPowerMeter.second, TrainsetPowerMeter.first + TrainsetPowerMeter.second);
if (TrainsetPowerMeter.first != 0.0 || TrainsetPowerMeter.second != 0.0)
{
std::snprintf(buffer.data(), buffer.size(), STR_C("Electricity usage:\n drawn: %.1f kWh\n returned: %.1f kWh\n balance: %.1f kWh"), TrainsetPowerMeter.first, -TrainsetPowerMeter.second,
TrainsetPowerMeter.first + TrainsetPowerMeter.second);
ImGui::TextUnformatted(buffer.data());
}
@@ -310,7 +271,8 @@ void ui::vehicleparams_panel::render_contents()
m_relay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name());
ImGui::SameLine();
if (ImGui::Button(STR_C("Reset position"))) {
if (ImGui::Button(STR_C("Reset position")))
{
std::string payload = vehicle_ptr->name() + '%' + vehicle_ptr->initial_track->name();
m_relay.post(user_command::consistteleport, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &payload);
m_relay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name());
@@ -330,7 +292,8 @@ void ui::vehicleparams_panel::render_contents()
if (ImGui::IsItemDeactivated())
m_relay.post(user_command::consistreleaser, 0.0, 0.0, GLFW_RELEASE, 0, glm::vec3(0.0f), &vehicle_ptr->name());
if (vehicle_ptr->MoverParameters->V < 0.01) {
if (vehicle_ptr->MoverParameters->V < 0.01)
{
if (ImGui::Button(STR_C("Move +500m")))
m_relay.post(user_command::dynamicmove, 500.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name());
ImGui::SameLine();