diff --git a/AirCoupler.cpp b/AirCoupler.cpp index 5c6c0b09..cbf67e24 100644 --- a/AirCoupler.cpp +++ b/AirCoupler.cpp @@ -10,6 +10,9 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "AirCoupler.h" +#include "model3d.h" +#include "parser.h" + TAirCoupler::TAirCoupler() { Clear(); diff --git a/AirCoupler.h b/AirCoupler.h index 8cdebaea..bb9cae27 100644 --- a/AirCoupler.h +++ b/AirCoupler.h @@ -9,8 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "Model3d.h" -#include "parser.h" +#include "classes.h" class TAirCoupler { diff --git a/AnimModel.cpp b/AnimModel.cpp index ac8bc679..1f34f67a 100644 --- a/AnimModel.cpp +++ b/AnimModel.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "AnimModel.h" +#include "renderer.h" #include "MdlMngr.h" #include "simulation.h" #include "Globals.h" @@ -71,11 +72,11 @@ int TAnimAdvanced::SortByBone() TAnimContainer::TAnimContainer() { pNext = NULL; - vRotateAngles = vector3(0.0f, 0.0f, 0.0f); // aktualne kąty obrotu - vDesiredAngles = vector3(0.0f, 0.0f, 0.0f); // docelowe kąty obrotu + vRotateAngles = Math3D::vector3(0.0f, 0.0f, 0.0f); // aktualne kąty obrotu + vDesiredAngles = Math3D::vector3(0.0f, 0.0f, 0.0f); // docelowe kąty obrotu fRotateSpeed = 0.0; - vTranslation = vector3(0.0f, 0.0f, 0.0f); // aktualne przesunięcie - vTranslateTo = vector3(0.0f, 0.0f, 0.0f); // docelowe przesunięcie + vTranslation = Math3D::vector3(0.0f, 0.0f, 0.0f); // aktualne przesunięcie + vTranslateTo = Math3D::vector3(0.0f, 0.0f, 0.0f); // docelowe przesunięcie fTranslateSpeed = 0.0; fAngleSpeed = 0.0; pSubModel = NULL; @@ -99,7 +100,7 @@ bool TAnimContainer::Init(TSubModel *pNewSubModel) return (pSubModel != NULL); } -void TAnimContainer::SetRotateAnim(vector3 vNewRotateAngles, double fNewRotateSpeed) +void TAnimContainer::SetRotateAnim( Math3D::vector3 vNewRotateAngles, double fNewRotateSpeed) { if (!this) return; // wywoływane z eventu, gdy brak modelu @@ -122,7 +123,7 @@ void TAnimContainer::SetRotateAnim(vector3 vNewRotateAngles, double fNewRotateSp } } -void TAnimContainer::SetTranslateAnim(vector3 vNewTranslate, double fNewSpeed) +void TAnimContainer::SetTranslateAnim( Math3D::vector3 vNewTranslate, double fNewSpeed) { if (!this) return; // wywoływane z eventu, gdy brak modelu @@ -153,8 +154,11 @@ void TAnimContainer::AnimSetVMD(double fNewSpeed) // X-w lewo, Y-w górę, Z-do tyłu // minimalna wysokość to -7.66, a nadal musi być ponad podłogą // if (pMovementData->iFrame>0) return; //tylko pierwsza ramka - vTranslateTo = vector3(0.1 * pMovementData->f3Vector.x, 0.1 * pMovementData->f3Vector.z, - 0.1 * pMovementData->f3Vector.y); + vTranslateTo = + Math3D::vector3( + 0.1 * pMovementData->f3Vector.x, + 0.1 * pMovementData->f3Vector.z, + 0.1 * pMovementData->f3Vector.y); if (LengthSquared3(vTranslateTo) > 0.0 ? true : LengthSquared3(vTranslation) > 0.0) { // jeśli ma być przesunięte albo jest przesunięcie iAnim |= 2; // wyłączy się samo @@ -209,11 +213,11 @@ void TAnimContainer::UpdateModel() { { if (fTranslateSpeed != 0.0) { - vector3 dif = vTranslateTo - vTranslation; // wektor w kierunku docelowym + auto dif = vTranslateTo - vTranslation; // wektor w kierunku docelowym double l = LengthSquared3(dif); // długość wektora potrzebnego przemieszczenia if (l >= 0.0001) { // jeśli do przemieszczenia jest ponad 1cm - vector3 s = SafeNormalize(dif); // jednostkowy wektor kierunku + auto s = Math3D::SafeNormalize(dif); // jednostkowy wektor kierunku s = s * (fTranslateSpeed * Timer::GetDeltaTime()); // przemieszczenie w podanym czasie z daną prędkością @@ -252,7 +256,7 @@ void TAnimContainer::UpdateModel() { */ bool anim = false; - vector3 dif = vDesiredAngles - vRotateAngles; + auto dif = vDesiredAngles - vRotateAngles; double s; s = fRotateSpeed * sign(dif.x) * Timer::GetDeltaTime(); if (fabs(s) >= fabs(dif.x)) @@ -462,7 +466,7 @@ bool TAnimModel::Load(cParser *parser, bool ter) name[ name.length() - 3 ] = 'e'; } #ifdef EU07_USE_OLD_TERRAINCODE - Global::asTerrainModel = name; + Global.asTerrainModel = name; WriteLog("Terrain model \"" + name + "\" will be created."); #endif } @@ -580,7 +584,7 @@ void TAnimModel::RaPrepare() state = ( fBlinkTimer < fOnTime ); break; case ls_Dark: // zapalone, gdy ciemno - state = ( Global::fLuminance <= ( lsLights[i] - 3.0 ) ); + state = ( Global.fLuminance <= ( lsLights[i] - 3.0 ) ); break; default: // zapalony albo zgaszony state = (lightmode == ls_On); diff --git a/AnimModel.h b/AnimModel.h index f581a96f..7cdb5248 100644 --- a/AnimModel.h +++ b/AnimModel.h @@ -14,9 +14,12 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "Model3d.h" -#include "material.h" -#include "DynObj.h" +#include "classes.h" +#include "dumb3d.h" +#include "float3d.h" +#include "model3d.h" +#include "dynobj.h" +#include "scenenode.h" const int iMaxNumLights = 8; float const DefaultDarkThresholdLevel { 0.325f }; @@ -47,11 +50,11 @@ class TAnimContainer friend class TAnimModel; private: - vector3 vRotateAngles; // dla obrotów Eulera - vector3 vDesiredAngles; + Math3D::vector3 vRotateAngles; // dla obrotów Eulera + Math3D::vector3 vDesiredAngles; double fRotateSpeed; - vector3 vTranslation; - vector3 vTranslateTo; + Math3D::vector3 vTranslation; + Math3D::vector3 vTranslateTo; double fTranslateSpeed; // może tu dać wektor? float4 qCurrent; // aktualny interpolowany float4 qStart; // pozycja początkowa (0 dla interpolacji) @@ -81,8 +84,8 @@ class TAnimContainer inline std::string NameGet() { return (pSubModel ? pSubModel->pName : ""); }; - void SetRotateAnim(vector3 vNewRotateAngles, double fNewRotateSpeed); - void SetTranslateAnim(vector3 vNewTranslate, double fNewSpeed); + void SetRotateAnim( Math3D::vector3 vNewRotateAngles, double fNewRotateSpeed); + void SetTranslateAnim( Math3D::vector3 vNewTranslate, double fNewSpeed); void AnimSetVMD(double fNewSpeed); void PrepareModel(); void UpdateModel(); @@ -92,8 +95,8 @@ class TAnimContainer double AngleGet() { return vRotateAngles.z; }; // jednak ostatnia, T3D ma inny układ inline - vector3 TransGet() { - return vector3(-vTranslation.x, vTranslation.z, vTranslation.y); }; // zmiana, bo T3D ma inny układ + Math3D::vector3 TransGet() { + return Math3D::vector3(-vTranslation.x, vTranslation.z, vTranslation.y); }; // zmiana, bo T3D ma inny układ inline void WillBeAnimated() { if (pSubModel) @@ -173,7 +176,7 @@ private: int iNumLights { 0 }; TSubModel *LightsOn[ iMaxNumLights ]; // Ra: te wskaźniki powinny być w ramach TModel3d TSubModel *LightsOff[ iMaxNumLights ]; - vector3 vAngle; // bazowe obroty egzemplarza względem osi + Math3D::vector3 vAngle; // bazowe obroty egzemplarza względem osi material_data m_materialdata; std::string asText; // tekst dla wyświetlacza znakowego diff --git a/Camera.cpp b/Camera.cpp index 4fc6d388..1be5d772 100644 --- a/Camera.cpp +++ b/Camera.cpp @@ -11,24 +11,24 @@ http://mozilla.org/MPL/2.0/. #include "Camera.h" #include "Globals.h" -#include "Usefull.h" +#include "utilities.h" #include "Console.h" #include "Timer.h" #include "mover.h" //--------------------------------------------------------------------------- -void TCamera::Init(vector3 NPos, vector3 NAngle) +void TCamera::Init( Math3D::vector3 NPos, Math3D::vector3 NAngle) { - vUp = vector3(0, 1, 0); - Velocity = vector3(0, 0, 0); + vUp = Math3D::vector3(0, 1, 0); + Velocity = Math3D::vector3(0, 0, 0); Pitch = NAngle.x; Yaw = NAngle.y; Roll = NAngle.z; Pos = NPos; - Type = (Global::bFreeFly ? tp_Free : tp_Follow); + Type = (Global.bFreeFly ? tp_Free : tp_Follow); }; void TCamera::OnCursorMove(double x, double y) { @@ -59,8 +59,8 @@ TCamera::OnCommand( command_data const &Command ) { case user_command::viewturn: { OnCursorMove( - reinterpret_cast( Command.param1 ) * 0.005 * Global::fMouseXScale / Global::ZoomFactor, - reinterpret_cast( Command.param2 ) * 0.01 * Global::fMouseYScale / Global::ZoomFactor ); + reinterpret_cast( Command.param1 ) * 0.005 * Global.fMouseXScale / Global.ZoomFactor, + reinterpret_cast( Command.param2 ) * 0.01 * Global.fMouseYScale / Global.ZoomFactor ); break; } @@ -154,7 +154,7 @@ void TCamera::Update() auto const deltatime = Timer::GetDeltaRenderTime(); // czas bez pauzy if( ( Type == tp_Free ) - || ( false == Global::ctrlState ) + || ( false == Global.ctrlState ) || ( true == DebugCameraFlag ) ) { // ctrl is used for mirror view, so we ignore the controls when in vehicle if ctrl is pressed // McZapkie-170402: poruszanie i rozgladanie we free takie samo jak w follow @@ -166,13 +166,13 @@ void TCamera::Update() if( ( Type == tp_Free ) || ( true == DebugCameraFlag ) ) { // free movement position update is handled here, movement while in vehicle is handled by train update - vector3 Vec = Velocity; + Math3D::vector3 Vec = Velocity; Vec.RotateY( Yaw ); Pos += Vec * 5.0 * deltatime; } } -vector3 TCamera::GetDirection() { +Math3D::vector3 TCamera::GetDirection() { return glm::normalize( glm::rotateY( glm::vec3{ 0.f, 0.f, 1.f }, Yaw ) ); } @@ -199,10 +199,10 @@ bool TCamera::SetMatrix( glm::dmat4 &Matrix ) { void TCamera::RaLook() { // zmiana kierunku patrzenia - przelicza Yaw - vector3 where = LookAt - Pos + vector3(0, 3, 0); // trochę w górę od szyn + Math3D::vector3 where = LookAt - Pos + Math3D::vector3(0, 3, 0); // trochę w górę od szyn if ((where.x != 0.0) || (where.z != 0.0)) Yaw = atan2(-where.x, -where.z); // kąt horyzontalny - double l = Length3(where); + double l = Math3D::Length3(where); if (l > 0.0) Pitch = asin(where.y / l); // kąt w pionie }; @@ -210,5 +210,5 @@ void TCamera::RaLook() void TCamera::Stop() { // wyłącznie bezwładnego ruchu po powrocie do kabiny Type = tp_Follow; - Velocity = vector3(0, 0, 0); + Velocity = Math3D::vector3(0, 0, 0); }; diff --git a/Camera.h b/Camera.h index ffb2e817..ba9bb0f6 100644 --- a/Camera.h +++ b/Camera.h @@ -10,11 +10,8 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "dumb3d.h" -#include "dynobj.h" #include "command.h" -using namespace Math3D; - //--------------------------------------------------------------------------- enum TCameraType { // tryby pracy kamery @@ -23,31 +20,30 @@ enum TCameraType tp_Satelite // widok z góry (nie używany) }; -class TCamera -{ +class TCamera { + private: - glm::dvec3 m_moverate; + glm::dvec3 m_moverate; public: // McZapkie: potrzebuje do kiwania na boki - double Pitch; - double Yaw; // w środku: 0=do przodu; na zewnątrz: 0=na południe - double Roll; - TCameraType Type; - vector3 Pos; // współrzędne obserwatora - vector3 LookAt; // współrzędne punktu, na który ma patrzeć - vector3 vUp; - vector3 Velocity; - void Init(vector3 NPos, vector3 NAngle); + void Init( Math3D::vector3 NPos, Math3D::vector3 NAngle); inline void Reset() { Pitch = Yaw = Roll = 0; }; void OnCursorMove(double const x, double const y); bool OnCommand( command_data const &Command ); void Update(); - vector3 GetDirection(); + Math3D::vector3 GetDirection(); bool SetMatrix(glm::dmat4 &Matrix); void RaLook(); void Stop(); - // bool GetMatrix(matrix4x4 &Matrix); - vector3 PtNext, PtPrev; + + TCameraType Type; + double Pitch; + double Yaw; // w środku: 0=do przodu; na zewnątrz: 0=na południe + double Roll; + Math3D::vector3 Pos; // współrzędne obserwatora + Math3D::vector3 LookAt; // współrzędne punktu, na który ma patrzeć + Math3D::vector3 vUp; + Math3D::vector3 Velocity; }; diff --git a/Classes.h b/Classes.h index 6f2b74d1..51ceaa35 100644 --- a/Classes.h +++ b/Classes.h @@ -16,22 +16,25 @@ class TTrack; // odcinek trajektorii class TEvent; class TTrain; // pojazd sterowany class TDynamicObject; // pojazd w scenerii -class TGroundNode; // statyczny obiekt scenerii +struct material_data; class TAnimModel; // opakowanie egzemplarz modelu class TAnimContainer; // fragment opakowania egzemplarza modelu class TModel3d; //siatka modelu wspólna dla egzemplarzy class TSubModel; // fragment modelu (tu do wyświetlania terenu) class TMemCell; // komórka pamięci class cParser; -#ifdef EU07_USE_OLD_SOUNDCODE -class TRealSound; // dźwięk ze współrzędnymi XYZ -class TTextSound; // dźwięk ze stenogramem -#else class sound_source; -#endif class TEventLauncher; class TTraction; // drut class TTractionPowerSource; // zasilanie drutów +class TCamera; +class TWorld; +class simulation_time; +class TMoverParameters; + +namespace scene { +struct node_data; +} namespace Mtable { diff --git a/Console.cpp b/Console.cpp index 7221435e..db6f2d1a 100644 --- a/Console.cpp +++ b/Console.cpp @@ -14,7 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "Logs.h" #include "MWD.h" // maciek001: obsluga portu COM #include "PoKeys55.h" -#include "mczapkie/mctools.h" +#include "utilities.h" //--------------------------------------------------------------------------- // Ra: klasa statyczna gromadząca sygnały sterujące oraz informacje zwrotne @@ -166,7 +166,7 @@ int Console::On() break; } - if (Global::bMWDmasterEnable) + if (Global.bMWDmasterEnable) { WriteLog("Opening ComPort"); MWDComm = new TMWDComm(); @@ -289,7 +289,7 @@ void Console::BitsUpdate(int mask) } break; } - if (Global::bMWDmasterEnable) + if (Global.bMWDmasterEnable) { // maciek001: MWDComm lampki i kontrolki // out3: ogrzewanie sk?adu, opory rozruchowe, poslizg, zaluzjewent, -, -, czuwak, shp @@ -343,7 +343,7 @@ void Console::BitsUpdate(int mask) bool Console::Pressed(int x) { // na razie tak - czyta się tylko klawiatura - if (glfwGetKey(Global::window, x) == GLFW_TRUE) + if (glfwGetKey(Global.window, x) == GLFW_TRUE) return true; else return false; @@ -354,79 +354,79 @@ void Console::ValueSet(int x, double y) if (iMode == 4) if (PoKeys55[0]) { - x = Global::iPoKeysPWM[x]; - if (Global::iCalibrateOutDebugInfo == x) + x = Global.iPoKeysPWM[x]; + if (Global.iCalibrateOutDebugInfo == x) WriteLog("CalibrateOutDebugInfo: oryginal=" + std::to_string(y)); - if (Global::fCalibrateOutMax[x] > 0) + if (Global.fCalibrateOutMax[x] > 0) { - y = clamp( y, 0.0, Global::fCalibrateOutMax[x]); - if (Global::iCalibrateOutDebugInfo == x) + y = clamp( y, 0.0, Global.fCalibrateOutMax[x]); + if (Global.iCalibrateOutDebugInfo == x) WriteLog(" cutted=" + std::to_string(y)); - y = y / Global::fCalibrateOutMax[x]; // sprowadzenie do <0,1> jeśli podana + y = y / Global.fCalibrateOutMax[x]; // sprowadzenie do <0,1> jeśli podana // maksymalna wartość - if (Global::iCalibrateOutDebugInfo == x) + if (Global.iCalibrateOutDebugInfo == x) WriteLog(" fraction=" + std::to_string(y)); } - double temp = (((((Global::fCalibrateOut[x][5] * y) + Global::fCalibrateOut[x][4]) * y + - Global::fCalibrateOut[x][3]) * + double temp = (((((Global.fCalibrateOut[x][5] * y) + Global.fCalibrateOut[x][4]) * y + + Global.fCalibrateOut[x][3]) * y + - Global::fCalibrateOut[x][2]) * + Global.fCalibrateOut[x][2]) * y + - Global::fCalibrateOut[x][1]) * + Global.fCalibrateOut[x][1]) * y + - Global::fCalibrateOut[x][0]; // zakres <0;1> - if (Global::iCalibrateOutDebugInfo == x) + Global.fCalibrateOut[x][0]; // zakres <0;1> + if (Global.iCalibrateOutDebugInfo == x) WriteLog(" calibrated=" + std::to_string(temp)); PoKeys55[0]->PWM(x, temp); } - if (Global::bMWDmasterEnable) + if (Global.bMWDmasterEnable) { unsigned int iliczba; switch (x) { - case 0: iliczba = (unsigned int)floor((y / (Global::fMWDzg[0] * 10) * Global::fMWDzg[1]) + 0.5); // zbiornik główny + case 0: iliczba = (unsigned int)floor((y / (Global.fMWDzg[0] * 10) * Global.fMWDzg[1]) + 0.5); // zbiornik główny MWDComm->WriteDataBuff[12] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[11] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Main tank press " + to_string(MWDComm->WriteDataBuff[12]) + " " + to_string(MWDComm->WriteDataBuff[11])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Main tank press " + to_string(MWDComm->WriteDataBuff[12]) + " " + to_string(MWDComm->WriteDataBuff[11])); break; - case 1: iliczba = (unsigned int)floor((y / (Global::fMWDpg[0] * 10) * Global::fMWDpg[1]) + 0.5); // przewód główny + case 1: iliczba = (unsigned int)floor((y / (Global.fMWDpg[0] * 10) * Global.fMWDpg[1]) + 0.5); // przewód główny MWDComm->WriteDataBuff[10] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[9] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Main pipe press " + to_string(MWDComm->WriteDataBuff[10]) + " " + to_string(MWDComm->WriteDataBuff[9])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Main pipe press " + to_string(MWDComm->WriteDataBuff[10]) + " " + to_string(MWDComm->WriteDataBuff[9])); break; - case 2: iliczba = (unsigned int)floor((y / (Global::fMWDph[0] * 10) * Global::fMWDph[1]) + 0.5); // cylinder hamulcowy + case 2: iliczba = (unsigned int)floor((y / (Global.fMWDph[0] * 10) * Global.fMWDph[1]) + 0.5); // cylinder hamulcowy MWDComm->WriteDataBuff[8] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[7] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Break press " + to_string(MWDComm->WriteDataBuff[8]) + " " + to_string(MWDComm->WriteDataBuff[7])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Break press " + to_string(MWDComm->WriteDataBuff[8]) + " " + to_string(MWDComm->WriteDataBuff[7])); break; - case 3: iliczba = (unsigned int)floor((y / Global::fMWDvolt[0] * Global::fMWDvolt[1]) + 0.5); // woltomierz WN + case 3: iliczba = (unsigned int)floor((y / Global.fMWDvolt[0] * Global.fMWDvolt[1]) + 0.5); // woltomierz WN MWDComm->WriteDataBuff[14] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[13] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Hi Volt meter " + to_string(MWDComm->WriteDataBuff[14]) + " " + to_string(MWDComm->WriteDataBuff[13])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Hi Volt meter " + to_string(MWDComm->WriteDataBuff[14]) + " " + to_string(MWDComm->WriteDataBuff[13])); break; - case 4: iliczba = (unsigned int)floor((y / Global::fMWDamp[0] * Global::fMWDamp[1]) + 0.5); // amp WN 1 + case 4: iliczba = (unsigned int)floor((y / Global.fMWDamp[0] * Global.fMWDamp[1]) + 0.5); // amp WN 1 MWDComm->WriteDataBuff[16] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[15] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Apm meter1 " + to_string(MWDComm->WriteDataBuff[16]) + " " + to_string(MWDComm->WriteDataBuff[15])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Apm meter1 " + to_string(MWDComm->WriteDataBuff[16]) + " " + to_string(MWDComm->WriteDataBuff[15])); break; - case 5: iliczba = (unsigned int)floor((y / Global::fMWDamp[0] * Global::fMWDamp[1]) + 0.5); // amp WN 2 + case 5: iliczba = (unsigned int)floor((y / Global.fMWDamp[0] * Global.fMWDamp[1]) + 0.5); // amp WN 2 MWDComm->WriteDataBuff[18] = (unsigned char)(iliczba >> 8); MWDComm->WriteDataBuff[17] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Apm meter2 " + to_string(MWDComm->WriteDataBuff[18]) + " " + to_string(MWDComm->WriteDataBuff[17])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Apm meter2 " + to_string(MWDComm->WriteDataBuff[18]) + " " + to_string(MWDComm->WriteDataBuff[17])); break; - case 6: iliczba = (unsigned int)floor((y / Global::fMWDamp[0] * Global::fMWDamp[1]) + 0.5); // amp WN 3 + case 6: iliczba = (unsigned int)floor((y / Global.fMWDamp[0] * Global.fMWDamp[1]) + 0.5); // amp WN 3 MWDComm->WriteDataBuff[20] = (unsigned int)(iliczba >> 8); MWDComm->WriteDataBuff[19] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Apm meter3 " + to_string(MWDComm->WriteDataBuff[20]) + " " + to_string(MWDComm->WriteDataBuff[19])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Apm meter3 " + to_string(MWDComm->WriteDataBuff[20]) + " " + to_string(MWDComm->WriteDataBuff[19])); break; - case 7: if (Global::iPause) MWDComm->WriteDataBuff[0] = 0; //skoro pauza to hasler stoi i nie nabija kilometrów CHYBA NIE DZIAŁA! + case 7: if (Global.iPause) MWDComm->WriteDataBuff[0] = 0; //skoro pauza to hasler stoi i nie nabija kilometrów CHYBA NIE DZIAŁA! else MWDComm->WriteDataBuff[0] = (unsigned char)floor(y); // prędkość dla np haslera - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Speed: " + to_string(MWDComm->WriteDataBuff[0])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Speed: " + to_string(MWDComm->WriteDataBuff[0])); break; - case 8: iliczba = (unsigned int)floor((y / Global::fMWDlowVolt[0] * Global::fMWDlowVolt[1]) + 0.5); // volt NN + case 8: iliczba = (unsigned int)floor((y / Global.fMWDlowVolt[0] * Global.fMWDlowVolt[1]) + 0.5); // volt NN MWDComm->WriteDataBuff[22] = (unsigned int)(iliczba >> 8); MWDComm->WriteDataBuff[21] = (unsigned char)iliczba; - if (Global::bMWDmasterEnable && Global::iMWDDebugMode & 8) WriteLog("Low Volt meter " + to_string(MWDComm->WriteDataBuff[22]) + " " + to_string(MWDComm->WriteDataBuff[21])); + if (Global.bMWDmasterEnable && Global.iMWDDebugMode & 8) WriteLog("Low Volt meter " + to_string(MWDComm->WriteDataBuff[22]) + " " + to_string(MWDComm->WriteDataBuff[21])); break; // przygotowane do wdrożenia, jeszcze nie wywoływane } } @@ -436,18 +436,18 @@ void Console::Update() { // funkcja powinna być wywoływana regularnie, np. raz w każdej ramce ekranowej if (iMode == 4) if (PoKeys55[0]) - if (PoKeys55[0]->Update((Global::iPause & 8) > 0)) + if (PoKeys55[0]->Update((Global.iPause & 8) > 0)) { // wykrycie przestawionych przełączników? - Global::iPause &= ~8; + Global.iPause &= ~8; } else { // błąd komunikacji - zapauzować symulację? - if (!(Global::iPause & 8)) // jeśli jeszcze nie oflagowana - Global::iTextMode = GLFW_KEY_F1; // pokazanie czasu/pauzy - Global::iPause |= 8; // tak??? + if (!(Global.iPause & 8)) // jeśli jeszcze nie oflagowana + Global.iTextMode = GLFW_KEY_F1; // pokazanie czasu/pauzy + Global.iPause |= 8; // tak??? PoKeys55[0]->Connect(); // próba ponownego podłączenia } - if (Global::bMWDmasterEnable) + if (Global.bMWDmasterEnable) { if (MWDComm->GetMWDState()) MWDComm->Run(); else MWDComm->Close(); @@ -467,19 +467,19 @@ float Console::AnalogCalibrateGet(int x) if (iMode == 4 && PoKeys55[0]) { float b = PoKeys55[0]->fAnalog[x]; - b = (((((Global::fCalibrateIn[x][5] * b) + Global::fCalibrateIn[x][4]) * b + - Global::fCalibrateIn[x][3]) * b + - Global::fCalibrateIn[x][2]) * b + - Global::fCalibrateIn[x][1]) * b + - Global::fCalibrateIn[x][0]; + b = (((((Global.fCalibrateIn[x][5] * b) + Global.fCalibrateIn[x][4]) * b + + Global.fCalibrateIn[x][3]) * b + + Global.fCalibrateIn[x][2]) * b + + Global.fCalibrateIn[x][1]) * b + + Global.fCalibrateIn[x][0]; if (x == 0) return (b + 2) / 8; if (x == 1) return b/10; else return b; } - if (Global::bMWDmasterEnable && Global::bMWDBreakEnable) + if (Global.bMWDmasterEnable && Global.bMWDBreakEnable) { float b = (float)MWDComm->uiAnalog[x]; - return (b - Global::fMWDAnalogInCalib[x][0]) / (Global::fMWDAnalogInCalib[x][1] - Global::fMWDAnalogInCalib[x][0]); + return (b - Global.fMWDAnalogInCalib[x][0]) / (Global.fMWDAnalogInCalib[x][1] - Global.fMWDAnalogInCalib[x][0]); } return -1.0; // odcięcie }; diff --git a/Console/MWD.cpp b/Console/MWD.cpp index 67b63bdd..9ea5adcb 100644 --- a/Console/MWD.cpp +++ b/Console/MWD.cpp @@ -79,7 +79,7 @@ TMWDComm::~TMWDComm() // destruktor bool TMWDComm::Open() // otwieranie portu COM { - LPCSTR portId = Global::sMWDPortId.c_str(); + LPCSTR portId = Global.sMWDPortId.c_str(); hComm = CreateFile(portId, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); @@ -99,7 +99,7 @@ bool TMWDComm::Open() // otwieranie portu COM CommDCB.DCBlength = sizeof(DCB); GetCommState(hComm, &CommDCB); - CommDCB.BaudRate = Global::iMWDBaudrate; + CommDCB.BaudRate = Global.iMWDBaudrate; CommDCB.fBinary = TRUE; CommDCB.fParity = FALSE; CommDCB.fOutxCtsFlow = FALSE; // No CTS output flow control @@ -133,9 +133,9 @@ bool TMWDComm::Open() // otwieranie portu COM bool TMWDComm::Close() // zamykanie portu COM { - Global::bMWDmasterEnable = false; // główne włączenie portu! - Global::bMWDInputEnable = false; // włącz wejścia - Global::bMWDBreakEnable = false; // włącz wejścia analogowe + Global.bMWDmasterEnable = false; // główne włączenie portu! + Global.bMWDInputEnable = false; // włącz wejścia + Global.bMWDBreakEnable = false; // włącz wejścia analogowe WriteLog("COM Port is closing..."); int i = 0; @@ -164,25 +164,25 @@ bool TMWDComm::ReadData() // odbieranie danych + odczyta danych analogowych i za { DWORD bytes_read; ReadFile(hComm, &ReadDataBuff[0], BYTETOREAD, &bytes_read, NULL); - if (Global::bMWDdebugEnable && Global::iMWDDebugMode == 128) WriteLog("Data receive. Checking data..."); - if (Global::bMWDBreakEnable) + if (Global.bMWDdebugEnable && Global.iMWDDebugMode == 128) WriteLog("Data receive. Checking data..."); + if (Global.bMWDBreakEnable) { uiAnalog[0] = (ReadDataBuff[9] << 8) + ReadDataBuff[8]; uiAnalog[1] = (ReadDataBuff[11] << 8) + ReadDataBuff[10]; uiAnalog[2] = (ReadDataBuff[13] << 8) + ReadDataBuff[12]; uiAnalog[3] = (ReadDataBuff[15] << 8) + ReadDataBuff[14]; - if (Global::bMWDdebugEnable && (Global::iMWDDebugMode & 1)) + if (Global.bMWDdebugEnable && (Global.iMWDDebugMode & 1)) { WriteLog("Main Break = " + to_string(uiAnalog[0])); WriteLog("Locomotiv Break = " + to_string(uiAnalog[1])); } - if (Global::bMWDdebugEnable && (Global::iMWDDebugMode & 2)) + if (Global.bMWDdebugEnable && (Global.iMWDDebugMode & 2)) { WriteLog("Analog input 1 = " + to_string(uiAnalog[2])); WriteLog("Analog imput 2 = " + to_string(uiAnalog[3])); } } - if (Global::bMWDInputEnable) CheckData(); + if (Global.bMWDInputEnable) CheckData(); return TRUE; } @@ -200,14 +200,14 @@ bool TMWDComm::Run() // wywoływanie obsługi MWD + generacja większego opóźn if (GetMWDState()) { MWDTime++; - if (!(MWDTime % Global::iMWDdivider)) + if (!(MWDTime % Global.iMWDdivider)) { MWDTime = 0; - if (Global::bMWDdebugEnable && Global::iMWDDebugMode == 128) WriteLog("Sending data..."); + if (Global.bMWDdebugEnable && Global.iMWDDebugMode == 128) WriteLog("Sending data..."); SendData(); - if (Global::bMWDdebugEnable && Global::iMWDDebugMode == 128) WriteLog(" complet!\nReceiving data..."); + if (Global.bMWDdebugEnable && Global.iMWDDebugMode == 128) WriteLog(" complet!\nReceiving data..."); ReadData(); - if (Global::bMWDdebugEnable && Global::iMWDDebugMode == 128) WriteLog(" complet!"); + if (Global.bMWDdebugEnable && Global.iMWDDebugMode == 128) WriteLog(" complet!"); return 1; } } diff --git a/Console/PoKeys55.cpp b/Console/PoKeys55.cpp index c27efaaf..abe24616 100644 --- a/Console/PoKeys55.cpp +++ b/Console/PoKeys55.cpp @@ -10,7 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "PoKeys55.h" #include -#include "mczapkie/mctools.h" +#include "utilities.h" + //--------------------------------------------------------------------------- // HIDscaner: http://forum.simflight.com/topic/68257-latest-lua-package-for-fsuipc-and-wideclient/ //#define MY_DEVICE_ID "Vid_04d8&Pid_003F" diff --git a/Driver.cpp b/Driver.cpp index 1dcb3123..b611b30d 100644 --- a/Driver.cpp +++ b/Driver.cpp @@ -23,8 +23,9 @@ http://mozilla.org/MPL/2.0/. #include "Event.h" #include "MemCell.h" #include "World.h" -#include "McZapkie/mctools.h" +#include "utilities.h" #include "McZapkie/MOVER.h" +#include "track.h" #define LOGVELOCITY 0 #define LOGORDERS 1 @@ -188,7 +189,7 @@ void TSpeedPos::Clear() fVelNext = -1.0; // prędkość bez ograniczeń fSectionVelocityDist = 0.0; //brak długości fDist = 0.0; - vPos = vector3(0, 0, 0); + vPos = Math3D::vector3(0, 0, 0); trTrack = NULL; // brak wskaźnika }; @@ -445,7 +446,7 @@ bool TController::TableNotFound(TEvent const *Event) const return ( ( true == TestFlag( speedpoint.iFlags, spEnabled | spEvent ) ) && ( speedpoint.evEvent == Event ) ); } ); - if( ( Global::iWriteLogEnabled & 8 ) + if( ( Global.iWriteLogEnabled & 8 ) && ( lookup != sSpeedTable.end() ) ) { WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->asName ); } @@ -533,7 +534,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) { if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony { // jeśli tor nie był jeszcze sprawdzany - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() ); } @@ -543,7 +544,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) { TableAddNew(); // zawsze jest true - if (Global::iWriteLogEnabled & 8) { + if (Global.iWriteLogEnabled & 8) { WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->asName); } auto &newspeedpoint = sSpeedTable[iLast]; @@ -563,7 +564,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) if (SemNextIndex == -1) { SemNextIndex = iLast; } - if (Global::iWriteLogEnabled & 8) { + if (Global.iWriteLogEnabled & 8) { WriteLog("(stop signal from " + (SemNextStopIndex != -1 ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")"); @@ -574,7 +575,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) && (SemNextIndex == -1)) { SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze } - if (Global::iWriteLogEnabled & 8) { + if (Global.iWriteLogEnabled & 8) { WriteLog("(forward signal for " + (SemNextIndex != -1 ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")"); @@ -730,7 +731,7 @@ void TController::TableCheck(double fDistance) { if (sSpeedTable[i].Update()) { - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" ); } // usuwamy wszystko za tym torem @@ -1006,8 +1007,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN if (go == cm_Unknown) // jeśli nie było komendy wcześniej go = cm_Ready; // gotów do odjazdu z W4 (semafor może // zatrzymać) - if( ( tsGuardSignal != nullptr ) - && ( false == tsGuardSignal->empty() ) ) { + if( false == tsGuardSignal.empty() ) { // jeśli mamy głos kierownika, to odegrać iDrivigFlags |= moveGuardSignal; } @@ -1060,14 +1060,14 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN // sprawdzanie eventów pasywnych miniętych if( (sSpeedTable[ i ].fDist < 0.0) && (SemNextIndex == i) ) { - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() ); } SemNextIndex = -1; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód } if( (sSpeedTable[ i ].fDist < 0.0) && (SemNextStopIndex == i) ) { - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() ); } SemNextStopIndex = -1; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód @@ -1079,7 +1079,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN // jeśli jest mienięty poprzedni semafor a wcześniej // byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy SemNextIndex = i; - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() ); } } @@ -1163,13 +1163,13 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN { if (sSpeedTable[i].fSectionVelocityDist == 0.0) { - if (Global::iWriteLogEnabled & 8) + if (Global.iWriteLogEnabled & 8) WriteLog("TableUpdate: Event is behind. SVD = 0: " + sSpeedTable[i].evEvent->asName); sSpeedTable[i].iFlags = 0; // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe } else if (sSpeedTable[i].fSectionVelocityDist < 0.0) { // ograniczenie obowiązujące do następnego - if (sSpeedTable[i].fVelNext == Global::Min0RSpeed(sSpeedTable[i].fVelNext, VelLimitLast) && + if (sSpeedTable[i].fVelNext == min_speed(sSpeedTable[i].fVelNext, VelLimitLast) && sSpeedTable[i].fVelNext != VelLimitLast) { // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz VelLimitLast = sSpeedTable[i].fVelNext; @@ -1177,14 +1177,14 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN else if (sSpeedTable[i].fDist < -fLength) { // jeśli większe to musi wyjechać za poprzednie VelLimitLast = sSpeedTable[i].fVelNext; - if (Global::iWriteLogEnabled & 8) + if (Global.iWriteLogEnabled & 8) WriteLog("TableUpdate: Event is behind. SVD < 0: " + sSpeedTable[i].evEvent->asName); sSpeedTable[i].iFlags = 0; // wyjechaliśmy poza poprzednie, można skasować } } else { // jeśli większe to ograniczenie ma swoją długość - if (sSpeedTable[i].fVelNext == Global::Min0RSpeed(sSpeedTable[i].fVelNext, VelLimitLast) && + if (sSpeedTable[i].fVelNext == min_speed(sSpeedTable[i].fVelNext, VelLimitLast) && sSpeedTable[i].fVelNext != VelLimitLast) { // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz VelLimitLast = sSpeedTable[i].fVelNext; @@ -1196,7 +1196,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN else if (sSpeedTable[i].fDist < -fLength - sSpeedTable[i].fSectionVelocityDist) { // VelLimitLast = -1.0; - if (Global::iWriteLogEnabled & 8) + if (Global.iWriteLogEnabled & 8) WriteLog("TableUpdate: Event is behind. SVD > 0: " + sSpeedTable[i].evEvent->asName); sSpeedTable[i].iFlags = 0; // wyjechaliśmy poza poprzednie, można skasować } @@ -1450,7 +1450,7 @@ void TController::TablePurger() // always copy the last entry trimmedtable.emplace_back( sSpeedTable.back() ); - if( Global::iWriteLogEnabled & 8 ) { + if( Global.iWriteLogEnabled & 8 ) { WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) ); } // update the data @@ -1571,7 +1571,6 @@ void TController::CloseLog() TController::~TController() { // wykopanie mechanika z roboty - delete tsGuardSignal; delete TrainParams; CloseLog(); }; @@ -1682,7 +1681,7 @@ void TController::Activation() } if (pVehicle != old) { // jeśli zmieniony został pojazd prowadzony - Global::pWorld->CabChange(old, pVehicle); // ewentualna zmiana kabiny użytkownikowi + Global.pWorld->CabChange(old, pVehicle); // ewentualna zmiana kabiny użytkownikowi ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - // silnikowy dla EZT } @@ -2583,8 +2582,7 @@ bool TController::IncSpeed() if (tsGuardSignal->GetStatus() & DSBSTATUS_PLAYING) // jeśli gada, to nie jedziemy return false; #else - if( ( tsGuardSignal != nullptr ) - && ( true == tsGuardSignal->is_playing() ) ) { + if( true == tsGuardSignal.is_playing() ) { return false; } #endif @@ -3076,12 +3074,11 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams = new TTrainParameters(NewCommand); // rozkład jazdy else TrainParams->NewName(NewCommand); // czyści tabelkę przystanków - delete tsGuardSignal; - tsGuardSignal = nullptr; // wywalenie kierownika + tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika if (NewCommand != "none") { if (!TrainParams->LoadTTfile( - std::string(Global::asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), + std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie { if (ConversionError == -8) @@ -3097,35 +3094,17 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N iStationStart = TrainParams->StationIndex; asNextStop = TrainParams->NextStop(); iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym - NewCommand = Global::asCurrentSceneryPath + NewCommand + ".wav"; // na razie jeden + NewCommand = Global.asCurrentSceneryPath + NewCommand + ".wav"; // na razie jeden if (FileExists(NewCommand)) { // wczytanie dźwięku odjazdu podawanego bezpośrenido -#ifdef EU07_USE_OLD_SOUNDCODE - tsGuardSignal = - new TTextSound( - NewCommand, 30, - pVehicle->GetPosition().x, pVehicle->GetPosition().y, pVehicle->GetPosition().z, - false); -#else - tsGuardSignal = new sound_source( sound_placement::external, 75.f ); - tsGuardSignal->deserialize( NewCommand, sound_type::single ); -#endif + tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( NewCommand, sound_type::single ); iGuardRadio = 0; // nie przez radio } else { NewCommand = NewCommand.insert(NewCommand.rfind('.'),"radio"); // wstawienie przed kropkč if (FileExists(NewCommand)) { // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) -#ifdef EU07_USE_OLD_SOUNDCODE - tsGuardSignal = - new TTextSound( - NewCommand, -1, - pVehicle->GetPosition().x, pVehicle->GetPosition().y, pVehicle->GetPosition().z, - false); -#else - tsGuardSignal = new sound_source( sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE ); - tsGuardSignal->deserialize( NewCommand, sound_type::single ); -#endif + tsGuardSignal = sound_source( sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE ).deserialize( NewCommand, sound_type::single ); iGuardRadio = iRadioChannel; } } @@ -3142,8 +3121,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset // nie podaje) { - vector3 v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - vector3 d = pVehicle->VectorFront(); // wektor wskazujący przód + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód iDirectionOrder = ((v.x * d.x + v.z * d.z) * NewValue1 > 0) ? 1 : -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie @@ -3266,8 +3245,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład // (trainset nie podaje) { - vector3 v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - vector3 d = pVehicle->VectorFront(); // wektor wskazujący przód + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód iDirectionOrder = ((v.x * d.x + v.z * d.z) * NewValue1 > 0) ? 1 : -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie @@ -3763,9 +3742,9 @@ TController::UpdateSituation(double dt) { pVehicles[ 0 ] : pVehicles[ 1 ] ); // for moving vehicle determine heading from velocity; for standing fall back on the set direction - if( ( mvOccupied->V != 0.0 ? - mvOccupied->V > 0.0 : - iDirection > 0 ) ) { + if( ( std::abs( mvOccupied->V ) < 0.1 ? // ignore potential micro-stutters in oposite direction during "almost stop" + iDirection > 0 : + mvOccupied->V > 0.0 ) ) { // towards coupler 0 if( ( mvOccupied->V * iDirection < 0.0 ) || ( ( rearvehicle->NextConnected != nullptr ) @@ -4164,7 +4143,7 @@ TController::UpdateSituation(double dt) { case Change_direction | Connect: // zmiana kierunku podczas podłączania if (OrderList[OrderPos] != Obey_train) // spokojne manewry { - VelSignal = Global::Min0RSpeed(VelSignal, 40); // jeśli manewry, to ograniczamy prędkość + VelSignal = min_speed( VelSignal, 40.0 ); // jeśli manewry, to ograniczamy prędkość // NOTE: this section should be moved to disconnect or plain removed, but it seems to be (mis)used by some scenarios // to keep vehicle idling without moving :| @@ -4282,7 +4261,7 @@ TController::UpdateSituation(double dt) { if( ( TrainParams ) && ( TrainParams->TTVmax > 0.0 ) ) { // jeśli ma rozkład i ograniczenie w rozkładzie to nie przekraczać rozkladowej - VelDesired = Global::Min0RSpeed( VelDesired, TrainParams->TTVmax ); + VelDesired = min_speed( VelDesired, TrainParams->TTVmax ); } SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) @@ -4403,7 +4382,7 @@ TController::UpdateSituation(double dt) { // jeśli spinanie, to jechać dalej AccPreferred = std::min( 0.25, AccPreferred ); // nie hamuj VelDesired = - Global::Min0RSpeed( + min_speed( VelDesired, ( vehicle->fTrackBlock > 150.0 ? 20.0: @@ -4432,7 +4411,7 @@ TController::UpdateSituation(double dt) { 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others // jak tamten jedzie wolniej a jest w drodze hamowania AccPreferred = std::min( -0.9, AccPreferred ); - VelNext = Global::Min0RSpeed( std::round( k ) - 5.0, VelDesired ); + VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); if( vehicle->fTrackBlock <= ( mvOccupied->CategoryFlag & 2 ? fMaxProximityDist : // cars @@ -4451,7 +4430,7 @@ TController::UpdateSituation(double dt) { if( OrderCurrentGet() & Connect ) { // if there's something nearby in the connect mode don't speed up too much VelDesired = - Global::Min0RSpeed( + min_speed( VelDesired, ( vehicle->fTrackBlock > 150.0 ? 20.0 : @@ -4479,28 +4458,28 @@ TController::UpdateSituation(double dt) { else if( VelSignal >= 0 ) { // jeśli skład był zatrzymany na początku i teraz już może jechać VelDesired = - Global::Min0RSpeed( + min_speed( VelDesired, VelSignal ); } if( mvOccupied->RunningTrack.Velmax >= 0 ) { // ograniczenie prędkości z trajektorii ruchu VelDesired = - Global::Min0RSpeed( + min_speed( VelDesired, mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! } if( VelforDriver >= 0 ) { // tu jest zero przy zmianie kierunku jazdy // Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70 - VelDesired = Global::Min0RSpeed( VelDesired, VelforDriver ); + VelDesired = min_speed( VelDesired, VelforDriver ); } if( ( TrainParams != nullptr ) && ( TrainParams->CheckTrainLatency() < 5.0 ) && ( TrainParams->TTVmax > 0.0 ) ) { // jesli nie spozniony to nie przekraczać rozkladowej VelDesired = - Global::Min0RSpeed( + min_speed( VelDesired, TrainParams->TTVmax ); } @@ -4514,19 +4493,8 @@ TController::UpdateSituation(double dt) { if (iDrivigFlags & moveGuardSignal) { // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania iDrivigFlags &= ~moveGuardSignal; // tylko raz nadać -/* - if( ( iDrivigFlags & moveDoorOpened ) - && ( false == mvOccupied->DoorOpenCtrl ) ) { - // jeśli drzwi otwarte, niesterowane przez maszynistę - Doors( false ); // a EZT zamknie dopiero po odegraniu komunikatu kierownika - } -*/ - if( tsGuardSignal != nullptr ) { -#ifdef EU07_USE_OLD_SOUNDCODE - tsGuardSignal->Stop(); -#else - tsGuardSignal->stop(); -#endif + if( false == tsGuardSignal.empty() ) { + tsGuardSignal.stop(); // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy // bezpośrednim // albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w @@ -4535,32 +4503,21 @@ TController::UpdateSituation(double dt) { // obsługę kanałów radiowych itd. if( iGuardRadio == 0 ) { // jeśli nie przez radio -#ifdef EU07_USE_OLD_SOUNDCODE - tsGuardSignal->Play( 1.0, 0, !FreeFlyModeFlag, pVehicle->GetPosition() ); // dla true jest głośniej -#else - tsGuardSignal->owner( pVehicle ); + tsGuardSignal.owner( pVehicle ); // place virtual conductor some distance away - tsGuardSignal->offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); - tsGuardSignal->play( sound_flags::exclusive ); -#endif + tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); + tsGuardSignal.play( sound_flags::exclusive ); } else { // if (iGuardRadio==iRadioChannel) //zgodność kanału // if (!FreeFlyModeFlag) //obserwator musi być w środku pojazdu // (albo może mieć radio przenośne) - kierownik mógłby powtarzać // przy braku reakcji -#ifdef EU07_USE_OLD_SOUNDCODE - if( SquareMagnitude( pVehicle->GetPosition() - Global::pCameraPosition ) < 2000 * 2000 ) { - // w odległości mniejszej niż 2km - tsGuardSignal->Play( 1.0, 0, true, pVehicle->GetPosition() ); // dźwięk niby przez radio - } -#else // TODO: proper system for sending/receiving radio messages // place the sound in appropriate cab of the manned vehicle - tsGuardSignal->owner( pVehicle ); - tsGuardSignal->offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->ActiveCab < 0 ? -1 : 1 ) } ); - tsGuardSignal->play( sound_flags::exclusive ); -#endif + tsGuardSignal.owner( pVehicle ); + tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->ActiveCab < 0 ? -1 : 1 ) } ); + tsGuardSignal.play( sound_flags::exclusive ); } } } @@ -4617,7 +4574,7 @@ TController::UpdateSituation(double dt) { // jak minął już maksymalny dystans po prostu hamuj (niski stopień) // ma stanąć, a jest w drodze hamowania albo ma jechać /* - VelDesired = Global::Min0RSpeed( VelDesired, VelNext ); + VelDesired = min_speed( VelDesired, VelNext ); */ if( VelNext == 0.0 ) { if( mvOccupied->CategoryFlag & 1 ) { @@ -4626,7 +4583,7 @@ TController::UpdateSituation(double dt) { && ( pVehicles[0]->fTrackBlock < 50.0 ) ) { // crude detection of edge case, if approaching another vehicle coast slowly until min distance // this should allow to bunch up trainsets more on sidings - VelDesired = Global::Min0RSpeed( VelDesired, 5.0 ); + VelDesired = min_speed( VelDesired, 5.0 ); } else { // hamowanie tak, aby stanąć @@ -4637,7 +4594,7 @@ TController::UpdateSituation(double dt) { } else { // for cars (and others) coast at low speed until we hit min proximity range - VelDesired = Global::Min0RSpeed( VelDesired, 5.0 ); + VelDesired = min_speed( VelDesired, 5.0 ); } } } @@ -4662,7 +4619,7 @@ TController::UpdateSituation(double dt) { // jest bliżej niż fMinProximityDist // utrzymuj predkosc bo juz blisko /* - VelDesired = Global::Min0RSpeed( VelDesired, VelNext ); + VelDesired = min_speed( VelDesired, VelNext ); */ if( VelNext == 0.0 ) { VelDesired = VelNext; @@ -5455,7 +5412,6 @@ TCommandType TController::BackwardScan() // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy return cm_Unknown; } - vector3 sl; // kierunek jazdy względem sprzęgów pojazdu na czele int const startdir = -pVehicles[0]->DirectionGet(); if( startdir == 0 ) { @@ -5472,7 +5428,7 @@ TCommandType TController::BackwardScan() TEvent *e = NULL; // event potencjalnie od semafora // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg drugiej osi w kierunku ruchu TTrack *scantrack = BackwardTraceRoute(scandist, scandir, pVehicles[0]->RaTrackGet(), e); - vector3 const dir = startdir * pVehicles[0]->VectorFront(); // wektor w kierunku jazdy/szukania + auto const dir = startdir * pVehicles[0]->VectorFront(); // wektor w kierunku jazdy/szukania if( !scantrack ) { // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić return cm_Unknown; @@ -5491,15 +5447,14 @@ TCommandType TController::BackwardScan() "Event1 " ) }; #endif // najpierw sprawdzamy, czy semafor czy inny znak został przejechany - vector3 pos = pVehicles[1]->RearPosition(); // pozycja tyłu - vector3 sem; // wektor do sygnału + auto pos = pVehicles[1]->RearPosition(); // pozycja tyłu if (e->Type == tp_GetValues) { // przesłać info o zbliżającym się semaforze #if LOGBACKSCAN edir += "(" + ( e->asNodeName ) + ")"; #endif - sl = e->PositionGet(); // położenie komórki pamięci - sem = sl - pos; // wektor do komórki pamięci od końca składu + auto sl = e->PositionGet(); // położenie komórki pamięci + auto sem = sl - pos; // wektor do komórki pamięci od końca składu if (dir.x * sem.x + dir.z * sem.z < 0) { // jeśli został minięty // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu diff --git a/Driver.h b/Driver.h index 966c0887..4161b7e8 100644 --- a/Driver.h +++ b/Driver.h @@ -9,13 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once -//#include -#include "Classes.h" -#include "dumb3d.h" -#include "mczapkie/mover.h" #include -using namespace Math3D; -using namespace Mtable; +#include "Classes.h" +#include "mczapkie/mover.h" +#include "sound.h" enum TOrders { // rozkazy dla AI @@ -134,7 +131,7 @@ class TSpeedPos // zwrotnicy,32-minięty,64=koniec,128=łuk // 0x100=event,0x200=manewrowa,0x400=przystanek,0x800=SBL,0x1000=wysłana komenda,0x2000=W5 // 0x4000=semafor,0x10000=zatkanie - vector3 vPos; // współrzędne XYZ do liczenia odległości + Math3D::vector3 vPos; // współrzędne XYZ do liczenia odległości struct { TTrack *trTrack{ nullptr }; // wskaźnik na tor o zmiennej prędkości (zwrotnica, obrotnica) @@ -238,13 +235,10 @@ private: TDynamicObject *pVehicles[2]; // skrajne pojazdy w składzie (niekoniecznie bezpośrednio sterowane) TMoverParameters *mvControlling = nullptr; // jakim pojazdem steruje (może silnikowym w EZT) TMoverParameters *mvOccupied = nullptr; // jakim pojazdem hamuje - TTrainParameters *TrainParams = nullptr; // rozkład jazdy zawsze jest, nawet jeśli pusty + Mtable::TTrainParameters *TrainParams = nullptr; // rozkład jazdy zawsze jest, nawet jeśli pusty int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) -/* - TTextSound *tsGuardSignal = nullptr; // komunikat od kierownika -*/ - sound_source *tsGuardSignal { nullptr }; + sound_source tsGuardSignal { sound_placement::internal }; public: double AccPreferred = 0.0; // preferowane przyspieszenie (wg psychiki kierującego, zmniejszana przy wykryciu kolizji) double AccDesired = AccPreferred; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj) @@ -265,7 +259,7 @@ private: public: double ActualProximityDist = 1.0; // odległość brana pod uwagę przy wyliczaniu prędkości i przyspieszenia private: - vector3 vCommandLocation; // polozenie wskaznika, sygnalizatora lub innego obiektu do ktorego + Math3D::vector3 vCommandLocation; // polozenie wskaznika, sygnalizatora lub innego obiektu do ktorego // odnosi sie komenda TOrders OrderList[maxorders]; // lista rozkazów int OrderPos = 0, diff --git a/DynObj.cpp b/DynObj.cpp index 21f91194..bf418a16 100644 --- a/DynObj.cpp +++ b/DynObj.cpp @@ -16,12 +16,15 @@ http://mozilla.org/MPL/2.0/. #include "DynObj.h" #include "simulation.h" +#include "world.h" #include "train.h" #include "Globals.h" #include "Timer.h" #include "logs.h" #include "Console.h" #include "MdlMngr.h" +#include "renderer.h" +#include "uitranscripts.h" // Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny #define vWorldFront Math3D::vector3(0, 0, 1) @@ -40,7 +43,7 @@ bool TDynamicObject::bDynamicRemove { false }; //--------------------------------------------------------------------------- void TAnimPant::AKP_4E() { // ustawienie wymiarów dla pantografu AKP-4E - vPos = vector3(0, 0, 0); // przypisanie domyśnych współczynników do pantografów + vPos = Math3D::vector3(0, 0, 0); // przypisanie domyśnych współczynników do pantografów fLenL1 = 1.22; // 1.176289 w modelach fLenU1 = 1.755; // 1.724482197 w modelach fHoriz = 0.535; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem @@ -287,7 +290,7 @@ odwrócony }; */ -void TDynamicObject::ABuSetModelShake(vector3 mShake) +void TDynamicObject::ABuSetModelShake( Math3D::vector3 mShake ) { modelShake = mShake; }; @@ -406,14 +409,14 @@ void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) if( pAnim->iNumber & 1 ) { pAnim->smAnimated->SetTranslate( - vector3{ + Math3D::vector3{ 0.0, 0.0, dDoorMoveR } ); } else { pAnim->smAnimated->SetTranslate( - vector3{ + Math3D::vector3{ 0.0, 0.0, dDoorMoveL } ); @@ -492,7 +495,7 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) if( pAnim->iNumber & 1 ) { pAnim->smAnimated->SetTranslate( - vector3 { + Math3D::vector3 { std::min( dDoorMoveR * 2, MoverParameters->DoorMaxPlugShift ), @@ -503,7 +506,7 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) } else { pAnim->smAnimated->SetTranslate( - vector3 { + Math3D::vector3 { std::min( dDoorMoveL * 2, MoverParameters->DoorMaxPlugShift ), @@ -629,7 +632,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // 'render' - juz // nie // przewody powietrzne, yB: decyzja na podstawie polaczen w t3d - if (Global::bnewAirCouplers) + if (Global.bnewAirCouplers) { SetPneumatic(false, false); // wczytywanie z t3d ulozenia wezykow SetPneumatic(true, false); // i zapisywanie do zmiennej @@ -809,10 +812,10 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) double dist = MoverParameters->Couplers[i].Dist / 2.0; if (smBuforLewy[i]) if (dist < 0) - smBuforLewy[i]->SetTranslate(vector3(dist, 0, 0)); + smBuforLewy[i]->SetTranslate( Math3D::vector3(dist, 0, 0)); if (smBuforPrawy[i]) if (dist < 0) - smBuforPrawy[i]->SetTranslate(vector3(dist, 0, 0)); + smBuforPrawy[i]->SetTranslate( Math3D::vector3(dist, 0, 0)); } } @@ -989,19 +992,19 @@ TDynamicObject * TDynamicObject::ABuFindNearestObject(TTrack *Track, TDynamicObj if( CouplNr == -2 ) { // wektor [kamera-obiekt] - poszukiwanie obiektu - if( LengthSquared3( Global::GetCameraPosition() - dynamic->vPosition ) < 100.0 ) { + if( LengthSquared3( Global.pCameraPosition - dynamic->vPosition ) < 100.0 ) { // 10 metrów return dynamic; } } else { // jeśli (CouplNr) inne niz -2, szukamy sprzęgu - if( LengthSquared3( Global::GetCameraPosition() - dynamic->vCoulpler[ 0 ] ) < 25.0 ) { + if( LengthSquared3( Global.pCameraPosition - dynamic->vCoulpler[ 0 ] ) < 25.0 ) { // 5 metrów CouplNr = 0; return dynamic; } - if( LengthSquared3( Global::GetCameraPosition() - dynamic->vCoulpler[ 1 ] ) < 25.0 ) { + if( LengthSquared3( Global.pCameraPosition - dynamic->vCoulpler[ 1 ] ) < 25.0 ) { // 5 metrów CouplNr = 1; return dynamic; @@ -1611,7 +1614,7 @@ void TDynamicObject::ABuScanObjects( int Direction, double Distance ) //----------ABu: koniec skanowania pojazdow TDynamicObject::TDynamicObject() { - modelShake = vector3(0, 0, 0); + modelShake = Math3D::vector3(0, 0, 0); fTrackBlock = 10000.0; // brak przeszkody na drodze btnOn = false; vUp = vWorldUp; @@ -1650,8 +1653,8 @@ TDynamicObject::TDynamicObject() { smBuforLewy[0] = smBuforLewy[1] = NULL; smBuforPrawy[0] = smBuforPrawy[1] = NULL; smBogie[0] = smBogie[1] = NULL; - bogieRot[0] = bogieRot[1] = vector3(0, 0, 0); - modelRot = vector3(0, 0, 0); + bogieRot[0] = bogieRot[1] = Math3D::vector3(0, 0, 0); + modelRot = Math3D::vector3(0, 0, 0); cp1 = cp2 = sp1 = sp2 = 0; iDirection = 1; // stoi w kierunku tradycyjnym (0, gdy jest odwrócony) iAxleFirst = 0; // numer pierwszej osi w kierunku ruchu (przełączenie @@ -2137,7 +2140,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // potem juz liczona prawidlowa wartosc masy MoverParameters->ComputeConstans(); // wektor podłogi dla wagonów, przesuwa ładunek - vFloor = vector3(0, 0, MoverParameters->Floor); + vFloor = Math3D::vector3(0, 0, MoverParameters->Floor); // długość większa od zera oznacza OK; 2mm docisku? return MoverParameters->Dim.L; @@ -2148,7 +2151,7 @@ TDynamicObject::create_controller( std::string const Type, bool const Trainset ) if( Type == "" ) { return; } - if( asName == Global::asHumanCtrlVehicle ) { + if( asName == Global.asHumanCtrlVehicle ) { // jeśli pojazd wybrany do prowadzenia if( MoverParameters->EngineType != Dumb ) { // wsadzamy tam sterującego @@ -2276,7 +2279,7 @@ void TDynamicObject::Move(double fDistance) // MoverParameters->Loc.Y= vPosition.z; // MoverParameters->Loc.Z= vPosition.y; // obliczanie pozycji sprzęgów do liczenia zderzeń - vector3 dir = (0.5 * MoverParameters->Dim.L) * vFront; // wektor sprzęgu + auto dir = (0.5 * MoverParameters->Dim.L) * vFront; // wektor sprzęgu vCoulpler[0] = vPosition + dir; // współrzędne sprzęgu na początku vCoulpler[1] = vPosition - dir; // współrzędne sprzęgu na końcu MoverParameters->vCoulpler[0] = vCoulpler[0]; // tymczasowo kopiowane na inny poziom @@ -2433,9 +2436,9 @@ void TDynamicObject::LoadUpdate() asBaseDir + MoverParameters->LoadType + ".t3d"; // zapamiętany katalog pojazdu // asLoadName=MoverParameters->LoadType; // if (MoverParameters->LoadType!=AnsiString("passengers")) - Global::asCurrentTexturePath = asBaseDir; // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; // bieżąca ścieżka do tekstur to dynamic/... mdLoad = TModelsManager::GetModel(asLoadName.c_str()); // nowy ładunek - Global::asCurrentTexturePath = + Global.asCurrentTexturePath = std::string(szTexturePath); // z powrotem defaultowa sciezka do tekstur // Ra: w MMD można by zapisać położenie modelu ładunku (np. węgiel) w // zależności od @@ -2580,7 +2583,7 @@ bool TDynamicObject::Update(double dt, double dt1) // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 - tp.friction = MyTrack->fFriction * Global::fFriction; + tp.friction = MyTrack->fFriction * Global.fFriction; tp.CategoryFlag = MyTrack->iCategoryFlag & 15; tp.DamageFlag = MyTrack->iDamageFlag; tp.QualityFlag = MyTrack->iQualityFlag; @@ -2605,7 +2608,7 @@ bool TDynamicObject::Update(double dt, double dt1) // tmpTraction.TractionVoltage=0; if (MoverParameters->EnginePowerSource.SourceType == CurrentCollector) { // dla EZT tylko silnikowy - // if (Global::bLiveTraction) + // if (Global.bLiveTraction) { // Ra 2013-12: to niżej jest chyba trochę bez sensu double v = MoverParameters->PantRearVolt; if (v == 0.0) { @@ -2932,7 +2935,6 @@ bool TDynamicObject::Update(double dt, double dt1) bDynamicRemove = true; // sprawdzić return false; } - Global::ABuDebug = dDOMoveLen / dt1; ResetdMoveLen(); // McZapkie-260202 @@ -3015,15 +3017,13 @@ bool TDynamicObject::Update(double dt, double dt1) { MoverParameters->DecMainCtrl(1); } */ - if ((!Console::Pressed(Global::Keys[k_IncMainCtrl])) && - (MoverParameters->MainCtrlPos > MoverParameters->MainCtrlActualPos)) - { - MoverParameters->DecMainCtrl(1); + if( ( glfwGetKey( Global.window, GLFW_KEY_KP_ADD ) != GLFW_TRUE ) + && ( MoverParameters->MainCtrlPos > MoverParameters->MainCtrlActualPos ) ) { + MoverParameters->DecMainCtrl( 1 ); } - if ((!Console::Pressed(Global::Keys[k_DecMainCtrl])) && - (MoverParameters->MainCtrlPos < MoverParameters->MainCtrlActualPos)) - { - MoverParameters->IncMainCtrl(1); // Ra 15-01: a to nie miało być tylko cofanie? + if( ( glfwGetKey( Global.window, GLFW_KEY_KP_SUBTRACT ) != GLFW_TRUE ) + && ( MoverParameters->MainCtrlPos < MoverParameters->MainCtrlActualPos ) ) { + MoverParameters->IncMainCtrl( 1 ); // Ra 15-01: a to nie miało być tylko cofanie? } } @@ -3087,7 +3087,7 @@ bool TDynamicObject::Update(double dt, double dt1) switch (i) // numer pantografu { // trzeba usunąć to rozróżnienie case 0: - if( ( Global::bLiveTraction == false ) + if( ( Global.bLiveTraction == false ) && ( p->hvPowerWire == nullptr ) ) { // jeśli nie ma drutu, może pooszukiwać MoverParameters->PantFrontVolt = @@ -3120,7 +3120,7 @@ bool TDynamicObject::Update(double dt, double dt1) MoverParameters->PantFrontVolt = 0.0; break; case 1: - if( ( false == Global::bLiveTraction ) + if( ( false == Global.bLiveTraction ) && ( nullptr == p->hvPowerWire ) ) { // jeśli nie ma drutu, może pooszukiwać MoverParameters->PantRearVolt = @@ -3149,7 +3149,7 @@ bool TDynamicObject::Update(double dt, double dt1) MoverParameters->PantRearVolt = 0.0; } else { -// Global::iPause ^= 2; +// Global.iPause ^= 2; MoverParameters->PantRearVolt = 0.0; } break; @@ -3479,7 +3479,7 @@ void TDynamicObject::TurnOff() // przeliczanie dźwięków, bo będzie słychać bez wyświetlania sektora z pojazdem void TDynamicObject::RenderSounds() { - if( Global::iPause != 0 ) { return; } + if( Global.iPause != 0 ) { return; } double const dt{ Timer::GetDeltaRenderTime() }; double volume{ 0.0 }; @@ -3698,10 +3698,10 @@ void TDynamicObject::RenderSounds() { && ( false == rsOuterNoise.empty() ) && ( // compound test whether the vehicle belongs to user-driven consist (as these don't emit outer noise in cab view) FreeFlyModeFlag ? true : // in external view all vehicles emit outer noise - // Global::pWorld->train() == nullptr ? true : // (can skip this check, with no player train the external view is a given) + // Global.pWorld->train() == nullptr ? true : // (can skip this check, with no player train the external view is a given) ctOwner == nullptr ? true : // standalone vehicle, can't be part of user-driven train - ctOwner != Global::pWorld->train()->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train - Global::CabWindowOpen ? true : // sticking head out we get to hear outer noise + ctOwner != Global.pWorld->train()->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train + Global.CabWindowOpen ? true : // sticking head out we get to hear outer noise false ) ) { // frequency calculation @@ -3867,7 +3867,7 @@ void TDynamicObject::RenderSounds() { void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, std::string ReplacableSkin ) { double dSDist; - Global::asCurrentDynamicPath = BaseDir; + Global.asCurrentDynamicPath = BaseDir; std::string asFileName = BaseDir + TypeName + ".mmd"; std::string asLoadName; if( false == MoverParameters->LoadType.empty() ) { @@ -3907,12 +3907,12 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, m_materialdata.multi_textures = clamp( m_materialdata.multi_textures, 0, 1 ); // na razie ustawiamy na 1 } asModel = BaseDir + asModel; // McZapkie 2002-07-20: dynamics maja swoje modele w dynamics/basedir - Global::asCurrentTexturePath = BaseDir; // biezaca sciezka do tekstur to dynamic/... + Global.asCurrentTexturePath = BaseDir; // biezaca sciezka do tekstur to dynamic/... mdModel = TModelsManager::GetModel(asModel, true); assert( mdModel != nullptr ); // TODO: handle this more gracefully than all going to shit if (ReplacableSkin != "none") { - std::string nowheretexture = TextureTest(Global::asCurrentTexturePath + "nowhere"); // na razie prymitywnie + std::string nowheretexture = TextureTest(Global.asCurrentTexturePath + "nowhere"); // na razie prymitywnie if( false == nowheretexture.empty() ) { m_materialdata.replacable_skins[ 4 ] = GfxRenderer.Fetch_Material( nowheretexture ); } @@ -3926,7 +3926,7 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, int skinindex = 0; std::string texturename; nameparser >> texturename; while( ( texturename != "" ) && ( skinindex < 4 ) ) { - m_materialdata.replacable_skins[ skinindex + 1 ] = GfxRenderer.Fetch_Material( Global::asCurrentTexturePath + texturename ); + m_materialdata.replacable_skins[ skinindex + 1 ] = GfxRenderer.Fetch_Material( Global.asCurrentTexturePath + texturename ); ++skinindex; texturename = ""; nameparser >> texturename; } @@ -3936,7 +3936,7 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, // otherwise try the basic approach int skinindex = 0; do { - material_handle material = GfxRenderer.Fetch_Material( Global::asCurrentTexturePath + ReplacableSkin + "," + std::to_string( skinindex + 1 ), true ); + material_handle material = GfxRenderer.Fetch_Material( Global.asCurrentTexturePath + ReplacableSkin + "," + std::to_string( skinindex + 1 ), true ); if( material == null_handle ) { break; } @@ -3946,12 +3946,12 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, m_materialdata.multi_textures = skinindex; if( m_materialdata.multi_textures == 0 ) { // zestaw nie zadziałał, próbujemy normanie - m_materialdata.replacable_skins[ 1 ] = GfxRenderer.Fetch_Material( Global::asCurrentTexturePath + ReplacableSkin ); + m_materialdata.replacable_skins[ 1 ] = GfxRenderer.Fetch_Material( Global.asCurrentTexturePath + ReplacableSkin ); } } } else { - m_materialdata.replacable_skins[ 1 ] = GfxRenderer.Fetch_Material( Global::asCurrentTexturePath + ReplacableSkin ); + m_materialdata.replacable_skins[ 1 ] = GfxRenderer.Fetch_Material( Global.asCurrentTexturePath + ReplacableSkin ); } if( GfxRenderer.Material( m_materialdata.replacable_skins[ 1 ] ).has_alpha ) { // tekstura -1 z kanałem alfa - nie renderować w cyklu nieprzezroczystych @@ -4024,7 +4024,7 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, } } } - Global::asCurrentTexturePath = szTexturePath; // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = szTexturePath; // z powrotem defaultowa sciezka do tekstur do { token = ""; parser.getTokens(); parser >> token; @@ -4043,7 +4043,7 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, parser.getTokens( 1, false ); parser >> ile; // ilość danego typu animacji // if (co==ANIM_PANTS) - // if (!Global::bLoadTraction) + // if (!Global.bLoadTraction) // if (!DebugModeFlag) //w debugmode pantografy mają "niby działać" // ile=0; //wyłączenie animacji pantografów if (co < ANIM_TYPES) @@ -4104,9 +4104,9 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, parser.getTokens(); parser >> asModel; asModel = BaseDir + asModel; // McZapkie-200702 - dynamics maja swoje modele w dynamic/basedir - Global::asCurrentTexturePath = BaseDir; // biezaca sciezka do tekstur to dynamic/... + Global.asCurrentTexturePath = BaseDir; // biezaca sciezka do tekstur to dynamic/... mdLowPolyInt = TModelsManager::GetModel(asModel, true); - // Global::asCurrentTexturePath=AnsiString(szTexturePath); //kiedyś uproszczone wnętrze mieszało tekstury nieba + // Global.asCurrentTexturePath=AnsiString(szTexturePath); //kiedyś uproszczone wnętrze mieszało tekstury nieba } if( token == "brakemode:" ) { @@ -4140,7 +4140,7 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); pAnimations[i].fMaxDist = 50 * MoverParameters->WheelDiameter; // nie kręcić w większej odległości pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist * MoverParameters->WheelDiameter; // 50m do kwadratu, a średnica do trzeciej - pAnimations[i].fMaxDist *= Global::fDistanceFactor; // współczynnik przeliczeniowy jakości ekranu + pAnimations[i].fMaxDist *= Global.fDistanceFactor; // współczynnik przeliczeniowy jakości ekranu } } // Ra: ustawianie indeksów osi @@ -4970,8 +4970,8 @@ void TDynamicObject::LoadMMediaFile( std::string BaseDir, std::string TypeName, if (mdLowPolyInt) mdLowPolyInt->Init(); - Global::asCurrentTexturePath = szTexturePath; // kiedyś uproszczone wnętrze mieszało tekstury nieba - Global::asCurrentDynamicPath = ""; + Global.asCurrentTexturePath = szTexturePath; // kiedyś uproszczone wnętrze mieszało tekstury nieba + Global.asCurrentDynamicPath = ""; // position sound emitters which weren't defined in the config file // engine sounds, centre of the vehicle @@ -5046,7 +5046,7 @@ void TDynamicObject::RadioStop() // add onscreen notification for human driver // TODO: do it selectively for the 'local' driver once the multiplayer is in if( false == Mechanik->AIControllFlag ) { - Global::tranTexts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); + ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); } } } @@ -5255,7 +5255,7 @@ void TDynamicObject::CoupleDist() // double d1=MoverParameters->Couplers[1].CoupleDist; //sprzęg z tyłu // samochodu można olać, // dopóki nie jeździ na wstecznym - vector3 p1, p2; + Math3D::vector3 p1, p2; double d, w; // dopuszczalny dystans w poprzek MoverParameters->SetCoupleDist(); // liczenie standardowe if (MoverParameters->Couplers[0].Connected) // jeśli cokolwiek podłączone @@ -5425,9 +5425,9 @@ void TDynamicObject::DestinationSet(std::string to, std::string numer) // jak są 4 tekstury wymienne, to nie zmieniać rozkładem return; } - numer = Global::Bezogonkow(numer); + numer = Bezogonkow(numer); asDestination = to; - to = Global::Bezogonkow(to); // do szukania pliku obcinamy ogonki + to = Bezogonkow(to); // do szukania pliku obcinamy ogonki std::vector destinations = { asBaseDir + numer + "@" + MoverParameters->TypeName, @@ -6020,7 +6020,7 @@ vehicle_table::update_traction( TDynamicObject *Vehicle ) { } if( ( pantograph->hvPowerWire == nullptr ) - && ( false == Global::bLiveTraction ) ) { + && ( false == Global.bLiveTraction ) ) { // jeśli drut nie znaleziony ale można oszukiwać to dajemy coś tam dla picu Vehicle->pants[ pantographindex ].fParamPants->PantTraction = 1.4; } diff --git a/DynObj.h b/DynObj.h index 9a3305bd..0f7f941f 100644 --- a/DynObj.h +++ b/DynObj.h @@ -12,12 +12,13 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "classes.h" +#include "material.h" +#include "mczapkie/mover.h" #include "TrkFoll.h" -// McZapkie: #include "Button.h" #include "AirCoupler.h" #include "sound.h" -#include "texture.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- diff --git a/EU07.cpp b/EU07.cpp index 361927cf..c39eb8b8 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -79,8 +79,8 @@ void screenshot_save_thread( char *img ) png_image png; memset(&png, 0, sizeof(png_image)); png.version = PNG_IMAGE_VERSION; - png.width = Global::iWindowWidth; - png.height = Global::iWindowHeight; + png.width = Global.iWindowWidth; + png.height = Global.iWindowHeight; png.format = PNG_FORMAT_RGB; char datetime[64]; @@ -96,7 +96,7 @@ void screenshot_save_thread( char *img ) std::string filename = "screenshots/" + std::string(datetime) + "_" + std::to_string(perf) + ".png"; - if (png_image_write_to_file(&png, filename.c_str(), 0, img, -Global::iWindowWidth * 3, nullptr) == 1) + if (png_image_write_to_file(&png, filename.c_str(), 0, img, -Global.iWindowWidth * 3, nullptr) == 1) WriteLog("saved " + filename + "."); else WriteLog("failed to save screenshot."); @@ -106,8 +106,8 @@ void screenshot_save_thread( char *img ) void make_screenshot() { - char *img = new char[Global::iWindowWidth * Global::iWindowHeight * 3]; - glReadPixels(0, 0, Global::iWindowWidth, Global::iWindowHeight, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)img); + char *img = new char[Global.iWindowWidth * Global.iWindowHeight * 3]; + glReadPixels(0, 0, Global.iWindowWidth, Global.iWindowHeight, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)img); std::thread t(screenshot_save_thread, img); t.detach(); @@ -118,9 +118,9 @@ void window_resize_callback(GLFWwindow *window, int w, int h) { // NOTE: we have two variables which basically do the same thing as we don't have dynamic fullscreen toggle // TBD, TODO: merge them? - Global::iWindowWidth = w; - Global::iWindowHeight = h; - Global::fDistanceFactor = std::max( 0.5f, h / 768.0f ); // not sure if this is really something we want to use + Global.iWindowWidth = w; + Global.iWindowHeight = h; + Global.fDistanceFactor = std::max( 0.5f, h / 768.0f ); // not sure if this is really something we want to use glViewport(0, 0, w, h); } @@ -128,7 +128,7 @@ void cursor_pos_callback(GLFWwindow *window, double x, double y) { input::Mouse.move( x, y ); - if( true == Global::ControlPicking ) { + if( true == Global.ControlPicking ) { glfwSetCursorPos( window, x, y ); } else { @@ -149,16 +149,16 @@ void key_callback( GLFWwindow *window, int key, int scancode, int action, int mo input::Keyboard.key( key, action ); - Global::shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false; - Global::ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false; + Global.shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false; + Global.ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false; - if( ( true == Global::InputMouse ) + if( ( true == Global.InputMouse ) && ( ( key == GLFW_KEY_LEFT_ALT ) || ( key == GLFW_KEY_RIGHT_ALT ) ) ) { // if the alt key was pressed toggle control picking mode and set matching cursor behaviour if( action == GLFW_RELEASE ) { - if( Global::ControlPicking ) { + if( Global.ControlPicking ) { // switch off glfwGetCursorPos( window, &input::mouse_pickmodepos.x, &input::mouse_pickmodepos.y ); glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); @@ -170,7 +170,7 @@ void key_callback( GLFWwindow *window, int key, int scancode, int action, int mo glfwSetCursorPos( window, input::mouse_pickmodepos.x, input::mouse_pickmodepos.y ); } // actually toggle the mode - Global::ControlPicking = !Global::ControlPicking; + Global.ControlPicking = !Global.ControlPicking; } } @@ -203,18 +203,18 @@ void key_callback( GLFWwindow *window, int key, int scancode, int action, int mo void focus_callback( GLFWwindow *window, int focus ) { - if( Global::bInactivePause ) // jeśli ma być pauzowanie okna w tle + if( Global.bInactivePause ) // jeśli ma być pauzowanie okna w tle if( focus ) - Global::iPause &= ~4; // odpauzowanie, gdy jest na pierwszym planie + Global.iPause &= ~4; // odpauzowanie, gdy jest na pierwszym planie else - Global::iPause |= 4; // włączenie pauzy, gdy nieaktywy + Global.iPause |= 4; // włączenie pauzy, gdy nieaktywy } void scroll_callback( GLFWwindow* window, double xoffset, double yoffset ) { - if( Global::ctrlState ) { + if( Global.ctrlState ) { // ctrl + scroll wheel adjusts fov in debug mode - Global::FieldOfView = clamp( static_cast(Global::FieldOfView - yoffset * 20.0 / Global::fFpsAverage), 15.0f, 75.0f ); + Global.FieldOfView = clamp( static_cast(Global.FieldOfView - yoffset * 20.0 / Global.fFpsAverage), 15.0f, 75.0f ); } } @@ -253,18 +253,17 @@ int main(int argc, char *argv[]) DeleteFile( "errors.txt" ); _mkdir("logs"); #endif - Global::LoadIniFile("eu07.ini"); - Global::InitKeys(); + Global.LoadIniFile("eu07.ini"); // hunter-271211: ukrywanie konsoli - if( Global::iWriteLogEnabled & 2 ) + if( Global.iWriteLogEnabled & 2 ) { AllocConsole(); SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN ); } /* std::string executable( argv[ 0 ] ); auto const pathend = executable.rfind( '\\' ); - Global::ExecutableName = + Global.ExecutableName = ( pathend != std::string::npos ? executable.substr( executable.rfind( '\\' ) + 1 ) : executable ); @@ -301,7 +300,7 @@ int main(int argc, char *argv[]) &stringdata, &datasize ) ) { - Global::asVersion = std::string( reinterpret_cast(stringdata) ); + Global.asVersion = std::string( reinterpret_cast(stringdata) ); } } } @@ -311,18 +310,18 @@ int main(int argc, char *argv[]) std::string token(argv[i]); if (token == "-e3d") { - if (Global::iConvertModels > 0) - Global::iConvertModels = -Global::iConvertModels; + if (Global.iConvertModels > 0) + Global.iConvertModels = -Global.iConvertModels; else - Global::iConvertModels = -7; // z optymalizacją, bananami i prawidłowym Opacity + Global.iConvertModels = -7; // z optymalizacją, bananami i prawidłowym Opacity } else if (i + 1 < argc && token == "-s") - Global::SceneryFile = std::string(argv[++i]); + Global.SceneryFile = std::string(argv[++i]); else if (i + 1 < argc && token == "-v") { std::string v(argv[++i]); std::transform(v.begin(), v.end(), v.begin(), ::tolower); - Global::asHumanCtrlVehicle = v; + Global.asHumanCtrlVehicle = v; } else { @@ -347,23 +346,23 @@ int main(int argc, char *argv[]) glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate); glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE); - if( Global::iMultisampling > 0 ) { - glfwWindowHint( GLFW_SAMPLES, 1 << Global::iMultisampling ); + if( Global.iMultisampling > 0 ) { + glfwWindowHint( GLFW_SAMPLES, 1 << Global.iMultisampling ); } - if (Global::bFullScreen) + if (Global.bFullScreen) { // match screen dimensions with selected monitor, for 'borderless window' in fullscreen mode - Global::iWindowWidth = vmode->width; - Global::iWindowHeight = vmode->height; + Global.iWindowWidth = vmode->width; + Global.iWindowHeight = vmode->height; } GLFWwindow *window = glfwCreateWindow( - Global::iWindowWidth, - Global::iWindowHeight, - Global::AppName.c_str(), - ( Global::bFullScreen ? + Global.iWindowWidth, + Global.iWindowHeight, + Global.AppName.c_str(), + ( Global.bFullScreen ? monitor : nullptr), nullptr ); @@ -374,7 +373,7 @@ int main(int argc, char *argv[]) return -1; } glfwMakeContextCurrent(window); - glfwSwapInterval(Global::VSync ? 1 : 0); //vsync + glfwSwapInterval(Global.VSync ? 1 : 0); //vsync glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //capture cursor glfwSetCursorPos(window, 0.0, 0.0); glfwSetFramebufferSizeCallback(window, window_resize_callback); @@ -415,7 +414,7 @@ int main(int argc, char *argv[]) input::Mouse.init(); input::Gamepad.init(); - Global::pWorld = &World; // Ra: wskaźnik potrzebny do usuwania pojazdów + Global.pWorld = &World; // Ra: wskaźnik potrzebny do usuwania pojazdów try { if( false == World.Init( window ) ) { ErrorLog( "Simulation setup failed" ); @@ -433,8 +432,8 @@ int main(int argc, char *argv[]) if( !joyGetNumDevs() ) WriteLog( "No joystick" ); */ - if( Global::iConvertModels < 0 ) { - Global::iConvertModels = -Global::iConvertModels; + if( Global.iConvertModels < 0 ) { + Global.iConvertModels = -Global.iConvertModels; World.CreateE3D( "models\\" ); // rekurencyjne przeglądanie katalogów World.CreateE3D( "dynamic\\", true ); } // po zrobieniu E3D odpalamy normalnie scenerię, by ją zobaczyć @@ -447,8 +446,8 @@ int main(int argc, char *argv[]) && ( true == GfxRenderer.Render() ) ) { glfwPollEvents(); input::Keyboard.poll(); - if( true == Global::InputMouse ) { input::Mouse.poll(); } - if( true == Global::InputGamepad ) { input::Gamepad.poll(); } + if( true == Global.InputMouse ) { input::Mouse.poll(); } + if( true == Global.InputGamepad ) { input::Gamepad.poll(); } } } catch( std::bad_alloc const &Error ) { diff --git a/EvLaunch.cpp b/EvLaunch.cpp index 38c23da1..72da61a1 100644 --- a/EvLaunch.cpp +++ b/EvLaunch.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "EvLaunch.h" + #include "Globals.h" #include "Logs.h" #include "Event.h" @@ -22,6 +23,8 @@ http://mozilla.org/MPL/2.0/. #include "Timer.h" #include "parser.h" #include "Console.h" +#include "world.h" +#include "utilities.h" //--------------------------------------------------------------------------- @@ -128,14 +131,14 @@ bool TEventLauncher::check_conditions() bool bCond = false; if (iKey != 0) { - if( Global::bActive ) { + if( Global.bActive ) { // tylko jeśli okno jest aktywne if( iKey > 255 ) { // key and modifier auto const modifier = ( iKey & 0xff00 ) >> 8; bCond = ( Console::Pressed( iKey & 0xff ) ) - && ( ( modifier & 1 ) ? Global::shiftState : true ) - && ( ( modifier & 2 ) ? Global::ctrlState : true ); + && ( ( modifier & 1 ) ? Global.shiftState : true ) + && ( ( modifier & 2 ) ? Global.ctrlState : true ); } else { // just key diff --git a/Event.cpp b/Event.cpp index 58d67788..1d0967dd 100644 --- a/Event.cpp +++ b/Event.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "event.h" #include "simulation.h" +#include "world.h" #include "globals.h" #include "timer.h" #include "logs.h" @@ -780,7 +781,7 @@ event_manager::insert( TEvent *Event ) { } auto *duplicate = m_events[ lookup->second ]; - if( Global::bJoinEvents ) { + if( Global.bJoinEvents ) { // doczepka (taki wirtualny multiple bez warunków) duplicate->Append( Event ); } @@ -959,7 +960,7 @@ event_manager::CheckQuery() { case tp_GetValues: { if( m_workevent->Activator ) { // TODO: re-enable when messaging module is in place - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { // potwierdzenie wykonania dla serwera (odczyt semafora już tak nie działa) multiplayer::WyslijEvent( m_workevent->asName, m_workevent->Activator->name() ); } @@ -1019,7 +1020,7 @@ event_manager::CheckQuery() { } case tp_Exit: { MessageBox( 0, m_workevent->asNodeName.c_str(), " THE END ", MB_OK ); - Global::iTextMode = -1; // wyłączenie takie samo jak sekwencja F10 -> Y + Global.iTextMode = -1; // wyłączenie takie samo jak sekwencja F10 -> Y return false; } case tp_Sound: { @@ -1034,7 +1035,7 @@ event_manager::CheckQuery() { } case 1: { if( m_workevent->Params[ 1 ].asdouble > 0.0 ) { - Global::pWorld->radio_message( + Global.pWorld->radio_message( m_workevent->Params[ 9 ].tsTextSound, static_cast( m_workevent->Params[ 1 ].asdouble ) ); } @@ -1098,7 +1099,7 @@ event_manager::CheckQuery() { m_workevent->Params[ 1 ].asdouble, m_workevent->Params[ 2 ].asdouble ); } - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { // dajemy znać do serwera o przełożeniu multiplayer::WyslijEvent( m_workevent->asName, "" ); // wysłanie nazwy eventu przełączajacego } @@ -1141,7 +1142,7 @@ event_manager::CheckQuery() { } } } - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { // dajemy znać do serwera o wykonaniu if( ( m_workevent->iFlags & conditional_anyelse ) == 0 ) { // jednoznaczne tylko, gdy nie było else @@ -1255,7 +1256,7 @@ event_manager::CheckQuery() { case tp_Friction: // zmiana tarcia na scenerii { // na razie takie chamskie ustawienie napięcia zasilania WriteLog("Type: Friction"); - Global::fFriction = (m_workevent->Params[0].asdouble); + Global.fFriction = (m_workevent->Params[0].asdouble); } break; case tp_Message: // wyświetlenie komunikatu diff --git a/Event.h b/Event.h index 642e4cbf..d6492795 100644 --- a/Event.h +++ b/Event.h @@ -9,11 +9,9 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include -#include "dumb3d.h" #include "classes.h" +#include "dumb3d.h" #include "names.h" -#include "scenenode.h" #include "evlaunch.h" enum TEventType { diff --git a/Globals.cpp b/Globals.cpp index 080bc445..275d70da 100644 --- a/Globals.cpp +++ b/Globals.cpp @@ -20,188 +20,19 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "PyInt.h" -// namespace Global { +global_settings Global; -// parametry do użytku wewnętrznego -std::string Global::AppName{ "EU07" }; -std::string Global::asCurrentSceneryPath = "scenery/"; -std::string Global::asCurrentTexturePath = std::string(szTexturePath); -std::string Global::asCurrentDynamicPath = ""; -int Global::iSlowMotion = 0; // info o malym FPS: 0-OK, 1-wyłączyć multisampling, 3-promień 1.5km, 7-1km -TDynamicObject *Global::changeDynObj = NULL; // info o zmianie pojazdu -double Global::ABuDebug = 0; -std::string Global::asSky = "1"; -double Global::fLuminance = 1.0; // jasność światła do automatycznego zapalania -float Global::SunAngle = 0.0f; -int Global::ScreenWidth = 1; -int Global::ScreenHeight = 1; -float Global::ZoomFactor = 1.0f; -float Global::FieldOfView = 45.0f; -GLFWwindow *Global::window; -bool Global::shiftState; -bool Global::ctrlState; -bool Global::CabWindowOpen { false }; -int Global::iCameraLast = -1; -std::string Global::asVersion = "couldn't retrieve version string"; -bool Global::ControlPicking = false; // indicates controls pick mode is enabled -bool Global::InputMouse = true; // whether control pick mode can be activated -int Global::iTextMode = 0; // tryb pracy wyświetlacza tekstowego -int Global::iScreenMode[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // numer ekranu wyświetlacza tekstowego -double Global::fTimeAngleDeg = 0.0; // godzina w postaci kąta -float Global::fClockAngleDeg[6]; // kąty obrotu cylindrów dla zegara cyfrowego -std::string Global::szTexturesTGA = ".tga"; // lista tekstur od TGA -std::string Global::szTexturesDDS = ".dds"; // lista tekstur od DDS -int Global::iPause = 0; // 0x10; // globalna pauza ruchu -bool Global::bActive = true; // czy jest aktywnym oknem -TWorld *Global::pWorld = NULL; -TCamera *Global::pCamera = NULL; // parametry kamery -TTranscripts Global::tranTexts; // obiekt obsługujący stenogramy dźwięków na ekranie -float4 Global::UITextColor = float4( 225.0 / 255.0f, 225.0f / 255.0f, 225.0f / 255.0f, 1.0f ); +void +global_settings::LoadIniFile(std::string asFileName) { -vector3 Global::pCameraPosition; -vector3 Global::DebugCameraPosition; -std::vector Global::FreeCameraInit; -std::vector Global::FreeCameraInitAngle; -// parametry scenerii -GLfloat Global::FogColor[] = {0.6f, 0.7f, 0.8f}; -double Global::fFogStart = 1700; -double Global::fFogEnd = 2000; -float Global::Overcast { 0.1f }; // NOTE: all this weather stuff should be moved elsewhere -std::string Global::Season; // season of the year, based on simulation date -std::string Global::Weather { "clear" }; // current weather - -float Global::BaseDrawRange { 2500.f }; -opengl_light Global::DayLight; -int Global::DynamicLightCount { 3 }; -bool Global::ScaleSpecularValues { true }; -bool Global::BasicRenderer { false }; -bool Global::RenderShadows { true }; -Global::shadowtune_t Global::shadowtune = { 2048, 250.f, 250.f, 500.f }; -bool Global::bRollFix = true; // czy wykonać przeliczanie przechyłki -bool Global::bJoinEvents = false; // czy grupować eventy o tych samych nazwach -int Global::iHiddenEvents = 1; // czy łączyć eventy z torami poprzez nazwę toru - -// parametry użytkowe (jak komu pasuje) -int Global::Keys[MaxKeys]; -bool Global::RealisticControlMode{ false }; -int Global::iWindowWidth = 800; -int Global::iWindowHeight = 600; -float Global::fDistanceFactor = Global::iWindowHeight / 768.0; // baza do przeliczania odległości dla LoD -int Global::iFeedbackMode = 1; // tryb pracy informacji zwrotnej -int Global::iFeedbackPort = 0; // dodatkowy adres dla informacji zwrotnych -bool Global::InputGamepad{ true }; -bool Global::bFreeFly = false; -bool Global::bFullScreen = false; -bool Global::VSync{ false }; -bool Global::bInactivePause = true; // automatyczna pauza, gdy okno nieaktywne -float Global::fMouseXScale = 1.5f; -float Global::fMouseYScale = 0.2f; -std::string Global::SceneryFile = "td.scn"; -std::string Global::asHumanCtrlVehicle = "EU07-424"; -int Global::iMultiplayer = 0; // blokada działania niektórych funkcji na rzecz komunikacji -double Global::fMoveLight = -1; // ruchome światło -bool Global::FakeLight{ false }; // toggle between fixed and dynamic daylight -double Global::fLatitudeDeg = 52.0; // szerokość geograficzna -float Global::fFriction = 1.0; // mnożnik tarcia - KURS90 -double Global::fBrakeStep = 1.0; // krok zmiany hamulca dla klawiszy [Num3] i [Num9] -std::string Global::asLang = "pl"; // domyślny język - http://tools.ietf.org/html/bcp47 - -// parametry wydajnościowe (np. regulacja FPS, szybkość wczytywania) -bool Global::bAdjustScreenFreq = true; -bool Global::bEnableTraction = true; -bool Global::bLoadTraction = true; -bool Global::bLiveTraction = true; -float Global::AnisotropicFiltering = 8.0f; // requested level of anisotropic filtering. TODO: move it to renderer object -bool Global::bUseVBO = true; // czy jest VBO w karcie graficznej (czy użyć) -std::string Global::LastGLError; -GLint Global::iMaxTextureSize = 4096; // maksymalny rozmiar tekstury -bool Global::bSmoothTraction { true }; // wygładzanie drutów starym sposobem -float Global::SplineFidelity { 1.f }; // determines segment size during conversion of splines to geometry -bool Global::ResourceSweep { true }; // gfx resource garbage collection -bool Global::ResourceMove { false }; // gfx resources are moved between cpu and gpu side instead of sending a copy -std::string Global::szDefaultExt = Global::szTexturesDDS; // domyślnie od DDS -int Global::iMultisampling = 2; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px -bool Global::DLFont{ false }; // switch indicating presence of basic font -bool Global::bGlutFont = false; // czy tekst generowany przez GLUT32.DLL -//int Global::iConvertModels = 7; // tworzenie plików binarnych, +2-optymalizacja transformów -int Global::iConvertModels{ 0 }; // temporary override, to prevent generation of .e3d not compatible with old exe -int Global::iSlowMotionMask = -1; // maska wyłączanych właściwości dla zwiększenia FPS -// bool Global::bTerrainCompact=true; //czy zapisać teren w pliku -double Global::fFpsAverage = 20.0; // oczekiwana wartosć FPS -double Global::fFpsDeviation = 5.0; // odchylenie standardowe FPS -double Global::fFpsMin = 30.0; // dolna granica FPS, przy której promień scenerii będzie zmniejszany -double Global::fFpsMax = 65.0; // górna granica FPS, przy której promień scenerii będzie zwiększany -bool Global::FullPhysics { true }; // full calculations performed for each simulation step - -// parametry testowe (do testowania scenerii i obiektów) -bool Global::bWireFrame = false; - -// sound renderer -bool Global::bSoundEnabled = true; -float Global::AudioVolume = 1.5f; -std::string Global::AudioRenderer; - -int Global::iWriteLogEnabled = 3; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów -bool Global::MultipleLogs { false }; -unsigned int Global::DisabledLogTypes { 0 }; - -// parametry do kalibracji -// kolejno współczynniki dla potęg 0, 1, 2, 3 wartości odczytanej z urządzenia -double Global::fCalibrateIn[6][6] = {{0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}}; -double Global::fCalibrateOut[7][6] = {{0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}, - {0, 1, 0, 0, 0, 0}}; -double Global::fCalibrateOutMax[7] = {0, 0, 0, 0, 0, 0, 0}; -int Global::iCalibrateOutDebugInfo = -1; -int Global::iPoKeysPWM[7] = {0, 1, 2, 3, 4, 5, 6}; -// parametry przejściowe (do usunięcia) -// bool Global::bTimeChange=false; //Ra: ZiomalCl wyłączył starą wersję nocy -// bool Global::bRenderAlpha=true; //Ra: wywaliłam tę flagę -bool Global::bnewAirCouplers = true; -double Global::fTimeSpeed = 1.0; // przyspieszenie czasu, zmienna do testów -bool Global::bHideConsole = false; // hunter-271211: ukrywanie konsoli -//randomizacja -std::mt19937 Global::random_engine = std::mt19937(std::time(NULL)); -// maciek001: konfiguracja wstępna portu COM -bool Global::bMWDmasterEnable = false; // główne włączenie portu! -bool Global::bMWDdebugEnable = false; // włącz dodawanie do logu -int Global::iMWDDebugMode = 0; // co ma wyświetlać w logu -std::string Global::sMWDPortId = "COM1"; // nazwa portu z którego korzystamy -unsigned long int Global::iMWDBaudrate = 9600; // prędkość transmisji danych -bool Global::bMWDInputEnable = false; // włącz wejścia -bool Global::bMWDBreakEnable = false; // włącz wejścia analogowe -double Global::fMWDAnalogInCalib[4][2] = { { 0, 1023 },{ 0, 1023 },{ 0, 1023 },{ 0, 1023 } }; // wartość max potencjometru, wartość min potencjometru, rozdzielczość (max. wartość jaka może być) -double Global::fMWDzg[2] = { 0.9, 1023 }; -double Global::fMWDpg[2] = { 0.8, 1023 }; -double Global::fMWDph[2] = { 0.6, 1023 }; -double Global::fMWDvolt[2] = { 4000, 1023 }; -double Global::fMWDamp[2] = { 800, 1023 }; -double Global::fMWDlowVolt[2] = { 150, 1023 }; -int Global::iMWDdivider = 5; - -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- - -void Global::LoadIniFile(std::string asFileName) -{ FreeCameraInit.resize( 10 ); FreeCameraInitAngle.resize( 10 ); cParser parser(asFileName, cParser::buffer_FILE); ConfigParse(parser); }; -void Global::ConfigParse(cParser &Parser) -{ +void +global_settings::ConfigParse(cParser &Parser) { std::string token; do @@ -215,66 +46,66 @@ void Global::ConfigParse(cParser &Parser) { Parser.getTokens(); - Parser >> Global::SceneryFile; + Parser >> SceneryFile; } else if (token == "humanctrlvehicle") { Parser.getTokens(); - Parser >> Global::asHumanCtrlVehicle; + Parser >> asHumanCtrlVehicle; } else if( token == "fieldofview" ) { Parser.getTokens( 1, false ); - Parser >> Global::FieldOfView; + Parser >> FieldOfView; // guard against incorrect values - Global::FieldOfView = clamp( Global::FieldOfView, 15.0f, 75.0f ); + FieldOfView = clamp( FieldOfView, 15.0f, 75.0f ); } else if (token == "width") { Parser.getTokens(1, false); - Parser >> Global::iWindowWidth; + Parser >> iWindowWidth; } else if (token == "height") { Parser.getTokens(1, false); - Parser >> Global::iWindowHeight; + Parser >> iWindowHeight; } else if (token == "heightbase") { Parser.getTokens(1, false); - Parser >> Global::fDistanceFactor; + Parser >> fDistanceFactor; } else if (token == "fullscreen") { Parser.getTokens(); - Parser >> Global::bFullScreen; + Parser >> bFullScreen; } else if( token == "vsync" ) { Parser.getTokens(); - Parser >> Global::VSync; + Parser >> VSync; } else if (token == "freefly") { // Mczapkie-130302 Parser.getTokens(); - Parser >> Global::bFreeFly; + Parser >> bFreeFly; Parser.getTokens(3, false); Parser >> - Global::FreeCameraInit[0].x, - Global::FreeCameraInit[0].y, - Global::FreeCameraInit[0].z; + FreeCameraInit[0].x, + FreeCameraInit[0].y, + FreeCameraInit[0].z; } else if (token == "wireframe") { Parser.getTokens(); - Parser >> Global::bWireFrame; + Parser >> bWireFrame; } else if (token == "debugmode") { // McZapkie! - DebugModeFlag uzywana w mover.pas, @@ -287,17 +118,17 @@ void Global::ConfigParse(cParser &Parser) // sie do debugowania oraz na komp. bez karty // dzw. Parser.getTokens(); - Parser >> Global::bSoundEnabled; + Parser >> bSoundEnabled; } else if( token == "sound.openal.renderer" ) { // selected device for audio renderer - Global::AudioRenderer = Parser.getToken( false ); // case-sensitive + AudioRenderer = Parser.getToken( false ); // case-sensitive } else if( token == "sound.volume" ) { // selected device for audio renderer Parser.getTokens(); - Parser >> Global::AudioVolume; - Global::AudioVolume = clamp( Global::AudioVolume, 1.f, 4.f ); + Parser >> AudioVolume; + AudioVolume = clamp( AudioVolume, 1.f, 4.f ); } // else if (str==AnsiString("renderalpha")) //McZapkie-1312302 - dwuprzebiegowe renderowanie // bRenderAlpha=(GetNextSymbol().LowerCase()==AnsiString("yes")); @@ -311,7 +142,7 @@ void Global::ConfigParse(cParser &Parser) { // McZapkie-291103 - usypianie fizyki Parser.getTokens(); - Parser >> Global::FullPhysics; + Parser >> FullPhysics; } else if (token == "debuglog") { @@ -320,73 +151,73 @@ void Global::ConfigParse(cParser &Parser) Parser >> token; if (token == "yes") { - Global::iWriteLogEnabled = 3; + iWriteLogEnabled = 3; } else if (token == "no") { - Global::iWriteLogEnabled = 0; + iWriteLogEnabled = 0; } else { - Global::iWriteLogEnabled = stol_def(token,3); + iWriteLogEnabled = stol_def(token,3); } } else if( token == "multiplelogs" ) { Parser.getTokens(); - Parser >> Global::MultipleLogs; + Parser >> MultipleLogs; } else if( token == "logs.filter" ) { Parser.getTokens(); - Parser >> Global::DisabledLogTypes; + Parser >> DisabledLogTypes; } else if( token == "adjustscreenfreq" ) { // McZapkie-240403 - czestotliwosc odswiezania ekranu Parser.getTokens(); - Parser >> Global::bAdjustScreenFreq; + Parser >> bAdjustScreenFreq; } else if (token == "mousescale") { // McZapkie-060503 - czulosc ruchu myszy (krecenia glowa) Parser.getTokens(2, false); - Parser >> Global::fMouseXScale >> Global::fMouseYScale; + Parser >> fMouseXScale >> fMouseYScale; } else if( token == "mousecontrol" ) { // whether control pick mode can be activated Parser.getTokens(); - Parser >> Global::InputMouse; + Parser >> InputMouse; } else if (token == "enabletraction") { // Winger 040204 - 'zywe' patyki dostosowujace sie do trakcji; Ra 2014-03: teraz łamanie Parser.getTokens(); - Parser >> Global::bEnableTraction; + Parser >> bEnableTraction; } else if (token == "loadtraction") { // Winger 140404 - ladowanie sie trakcji Parser.getTokens(); - Parser >> Global::bLoadTraction; + Parser >> bLoadTraction; } else if (token == "friction") { // mnożnik tarcia - KURS90 Parser.getTokens(1, false); - Parser >> Global::fFriction; + Parser >> fFriction; } else if (token == "livetraction") { // Winger 160404 - zaleznosc napiecia loka od trakcji; // Ra 2014-03: teraz prąd przy braku sieci Parser.getTokens(); - Parser >> Global::bLiveTraction; + Parser >> bLiveTraction; } else if (token == "skyenabled") { // youBy - niebo Parser.getTokens(); Parser >> token; - Global::asSky = (token == "yes" ? "1" : "0"); + asSky = (token == "yes" ? "1" : "0"); } else if (token == "defaultext") { @@ -396,10 +227,10 @@ void Global::ConfigParse(cParser &Parser) if (token == "tga") { // domyślnie od TGA - Global::szDefaultExt = Global::szTexturesTGA; + szDefaultExt = szTexturesTGA; } else { - Global::szDefaultExt = + szDefaultExt = ( token[ 0 ] == '.' ? token : "." + token ); @@ -409,36 +240,36 @@ void Global::ConfigParse(cParser &Parser) { Parser.getTokens(); - Parser >> Global::bnewAirCouplers; + Parser >> bnewAirCouplers; } else if( token == "anisotropicfiltering" ) { Parser.getTokens( 1, false ); - Parser >> Global::AnisotropicFiltering; + Parser >> AnisotropicFiltering; } else if( token == "usevbo" ) { Parser.getTokens(); - Parser >> Global::bUseVBO; + Parser >> bUseVBO; } else if (token == "feedbackmode") { Parser.getTokens(1, false); - Parser >> Global::iFeedbackMode; + Parser >> iFeedbackMode; } else if (token == "feedbackport") { Parser.getTokens(1, false); - Parser >> Global::iFeedbackPort; + Parser >> iFeedbackPort; } else if (token == "multiplayer") { Parser.getTokens(1, false); - Parser >> Global::iMultiplayer; + Parser >> iMultiplayer; } else if (token == "maxtexturesize") { @@ -446,155 +277,155 @@ void Global::ConfigParse(cParser &Parser) Parser.getTokens(1, false); int size; Parser >> size; - if (size <= 64) { Global::iMaxTextureSize = 64; } - else if (size <= 128) { Global::iMaxTextureSize = 128; } - else if (size <= 256) { Global::iMaxTextureSize = 256; } - else if (size <= 512) { Global::iMaxTextureSize = 512; } - else if (size <= 1024) { Global::iMaxTextureSize = 1024; } - else if (size <= 2048) { Global::iMaxTextureSize = 2048; } - else if (size <= 4096) { Global::iMaxTextureSize = 4096; } - else if (size <= 8192) { Global::iMaxTextureSize = 8192; } - else { Global::iMaxTextureSize = 16384; } + if (size <= 64) { iMaxTextureSize = 64; } + else if (size <= 128) { iMaxTextureSize = 128; } + else if (size <= 256) { iMaxTextureSize = 256; } + else if (size <= 512) { iMaxTextureSize = 512; } + else if (size <= 1024) { iMaxTextureSize = 1024; } + else if (size <= 2048) { iMaxTextureSize = 2048; } + else if (size <= 4096) { iMaxTextureSize = 4096; } + else if (size <= 8192) { iMaxTextureSize = 8192; } + else { iMaxTextureSize = 16384; } } else if (token == "movelight") { // numer dnia w roku albo -1 Parser.getTokens(1, false); - Parser >> Global::fMoveLight; - if (Global::fMoveLight == 0.f) + Parser >> fMoveLight; + if (fMoveLight == 0.f) { // pobranie daty z systemu std::time_t timenow = std::time(0); std::tm *localtime = std::localtime(&timenow); - Global::fMoveLight = localtime->tm_yday + 1; // numer bieżącego dnia w roku + fMoveLight = localtime->tm_yday + 1; // numer bieżącego dnia w roku } - Global::pWorld->compute_season( Global::fMoveLight ); + pWorld->compute_season( fMoveLight ); } else if( token == "dynamiclights" ) { // number of dynamic lights in the scene Parser.getTokens( 1, false ); - Parser >> Global::DynamicLightCount; + Parser >> DynamicLightCount; // clamp the light number // max 8 lights per opengl specs, minus one used for sun. at least one light for controlled vehicle - Global::DynamicLightCount = clamp( Global::DynamicLightCount, 1, 7 ); + DynamicLightCount = clamp( DynamicLightCount, 1, 7 ); } else if( token == "scalespeculars" ) { // whether strength of specular highlights should be adjusted (generally needed for legacy 3d models) Parser.getTokens(); - Parser >> Global::ScaleSpecularValues; + Parser >> ScaleSpecularValues; } else if( token == "gfxrenderer" ) { // shadow render toggle std::string gfxrenderer; Parser.getTokens(); Parser >> gfxrenderer; - Global::BasicRenderer = ( gfxrenderer == "simple" ); + BasicRenderer = ( gfxrenderer == "simple" ); } else if( token == "shadows" ) { // shadow render toggle Parser.getTokens(); - Parser >> Global::RenderShadows; + Parser >> RenderShadows; } else if( token == "shadowtune" ) { Parser.getTokens( 4, false ); Parser - >> Global::shadowtune.map_size - >> Global::shadowtune.width - >> Global::shadowtune.depth - >> Global::shadowtune.distance; + >> shadowtune.map_size + >> shadowtune.width + >> shadowtune.depth + >> shadowtune.distance; } else if (token == "smoothtraction") { // podwójna jasność ambient Parser.getTokens(); - Parser >> Global::bSmoothTraction; + Parser >> bSmoothTraction; } else if( token == "splinefidelity" ) { // segment size during spline->geometry conversion float splinefidelity; Parser.getTokens(); Parser >> splinefidelity; - Global::SplineFidelity = clamp( splinefidelity, 1.f, 4.f ); + SplineFidelity = clamp( splinefidelity, 1.f, 4.f ); } else if( token == "gfx.resource.sweep" ) { Parser.getTokens(); - Parser >> Global::ResourceSweep; + Parser >> ResourceSweep; } else if( token == "gfx.resource.move" ) { Parser.getTokens(); - Parser >> Global::ResourceMove; + Parser >> ResourceMove; } else if (token == "timespeed") { // przyspieszenie czasu, zmienna do testów Parser.getTokens(1, false); - Parser >> Global::fTimeSpeed; + Parser >> fTimeSpeed; } else if (token == "multisampling") { // tryb antyaliasingu: 0=brak,1=2px,2=4px Parser.getTokens(1, false); - Parser >> Global::iMultisampling; + Parser >> iMultisampling; } else if (token == "glutfont") { // tekst generowany przez GLUT Parser.getTokens(); - Parser >> Global::bGlutFont; + Parser >> bGlutFont; } else if (token == "latitude") { // szerokość geograficzna Parser.getTokens(1, false); - Parser >> Global::fLatitudeDeg; + Parser >> fLatitudeDeg; } else if (token == "convertmodels") { // tworzenie plików binarnych Parser.getTokens(1, false); - Parser >> Global::iConvertModels; + Parser >> iConvertModels; // temporary override, to prevent generation of .e3d not compatible with old exe - Global::iConvertModels = - ( Global::iConvertModels > 128 ? - Global::iConvertModels - 128 : + iConvertModels = + ( iConvertModels > 128 ? + iConvertModels - 128 : 0 ); } else if (token == "inactivepause") { // automatyczna pauza, gdy okno nieaktywne Parser.getTokens(); - Parser >> Global::bInactivePause; + Parser >> bInactivePause; } else if (token == "slowmotion") { // tworzenie plików binarnych Parser.getTokens(1, false); - Parser >> Global::iSlowMotionMask; + Parser >> iSlowMotionMask; } else if (token == "hideconsole") { // hunter-271211: ukrywanie konsoli Parser.getTokens(); - Parser >> Global::bHideConsole; + Parser >> bHideConsole; } else if (token == "rollfix") { // Ra: poprawianie przechyłki, aby wewnętrzna szyna była "pozioma" Parser.getTokens(); - Parser >> Global::bRollFix; + Parser >> bRollFix; } else if (token == "fpsaverage") { // oczekiwana wartość FPS Parser.getTokens(1, false); - Parser >> Global::fFpsAverage; + Parser >> fFpsAverage; } else if (token == "fpsdeviation") { // odchylenie standardowe FPS Parser.getTokens(1, false); - Parser >> Global::fFpsDeviation; + Parser >> fFpsDeviation; } else if (token == "calibratein") { @@ -608,12 +439,12 @@ void Global::ConfigParse(cParser &Parser) } Parser.getTokens(4, false); Parser - >> Global::fCalibrateIn[in][0] // wyraz wolny - >> Global::fCalibrateIn[in][1] // mnożnik - >> Global::fCalibrateIn[in][2] // mnożnik dla kwadratu - >> Global::fCalibrateIn[in][3]; // mnożnik dla sześcianu - Global::fCalibrateIn[in][4] = 0.0; // mnożnik 4 potęgi - Global::fCalibrateIn[in][5] = 0.0; // mnożnik 5 potęgi + >> fCalibrateIn[in][0] // wyraz wolny + >> fCalibrateIn[in][1] // mnożnik + >> fCalibrateIn[in][2] // mnożnik dla kwadratu + >> fCalibrateIn[in][3]; // mnożnik dla sześcianu + fCalibrateIn[in][4] = 0.0; // mnożnik 4 potęgi + fCalibrateIn[in][5] = 0.0; // mnożnik 5 potęgi } else if (token == "calibrate5din") { @@ -626,12 +457,12 @@ void Global::ConfigParse(cParser &Parser) in = 5; // na ostatni, bo i tak trzeba pominąć wartości } Parser.getTokens(6, false); - Parser >> Global::fCalibrateIn[in][0] // wyraz wolny - >> Global::fCalibrateIn[in][1] // mnożnik - >> Global::fCalibrateIn[in][2] // mnożnik dla kwadratu - >> Global::fCalibrateIn[in][3] // mnożnik dla sześcianu - >> Global::fCalibrateIn[in][4] // mnożnik 4 potęgi - >> Global::fCalibrateIn[in][5]; // mnożnik 5 potęgi + Parser >> fCalibrateIn[in][0] // wyraz wolny + >> fCalibrateIn[in][1] // mnożnik + >> fCalibrateIn[in][2] // mnożnik dla kwadratu + >> fCalibrateIn[in][3] // mnożnik dla sześcianu + >> fCalibrateIn[in][4] // mnożnik 4 potęgi + >> fCalibrateIn[in][5]; // mnożnik 5 potęgi } else if (token == "calibrateout") { @@ -644,12 +475,12 @@ void Global::ConfigParse(cParser &Parser) out = 6; // na ostatni, bo i tak trzeba pominąć wartości } Parser.getTokens(4, false); - Parser >> Global::fCalibrateOut[out][0] // wyraz wolny - >> Global::fCalibrateOut[out][1] // mnożnik liniowy - >> Global::fCalibrateOut[out][2] // mnożnik dla kwadratu - >> Global::fCalibrateOut[out][3]; // mnożnik dla sześcianu - Global::fCalibrateOut[out][4] = 0.0; // mnożnik dla 4 potęgi - Global::fCalibrateOut[out][5] = 0.0; // mnożnik dla 5 potęgi + Parser >> fCalibrateOut[out][0] // wyraz wolny + >> fCalibrateOut[out][1] // mnożnik liniowy + >> fCalibrateOut[out][2] // mnożnik dla kwadratu + >> fCalibrateOut[out][3]; // mnożnik dla sześcianu + fCalibrateOut[out][4] = 0.0; // mnożnik dla 4 potęgi + fCalibrateOut[out][5] = 0.0; // mnożnik dla 5 potęgi } else if (token == "calibrate5dout") { @@ -662,27 +493,27 @@ void Global::ConfigParse(cParser &Parser) out = 6; // na ostatni, bo i tak trzeba pominąć wartości } Parser.getTokens(6, false); - Parser >> Global::fCalibrateOut[out][0] // wyraz wolny - >> Global::fCalibrateOut[out][1] // mnożnik liniowy - >> Global::fCalibrateOut[out][2] // mnożnik dla kwadratu - >> Global::fCalibrateOut[out][3] // mnożnik dla sześcianu - >> Global::fCalibrateOut[out][4] // mnożnik dla 4 potęgi - >> Global::fCalibrateOut[out][5]; // mnożnik dla 5 potęgi + Parser >> fCalibrateOut[out][0] // wyraz wolny + >> fCalibrateOut[out][1] // mnożnik liniowy + >> fCalibrateOut[out][2] // mnożnik dla kwadratu + >> fCalibrateOut[out][3] // mnożnik dla sześcianu + >> fCalibrateOut[out][4] // mnożnik dla 4 potęgi + >> fCalibrateOut[out][5]; // mnożnik dla 5 potęgi } else if (token == "calibrateoutmaxvalues") { // maksymalne wartości jakie można wyświetlić na mierniku Parser.getTokens(7, false); - Parser >> Global::fCalibrateOutMax[0] >> Global::fCalibrateOutMax[1] >> - Global::fCalibrateOutMax[2] >> Global::fCalibrateOutMax[3] >> - Global::fCalibrateOutMax[4] >> Global::fCalibrateOutMax[5] >> - Global::fCalibrateOutMax[6]; + Parser >> fCalibrateOutMax[0] >> fCalibrateOutMax[1] >> + fCalibrateOutMax[2] >> fCalibrateOutMax[3] >> + fCalibrateOutMax[4] >> fCalibrateOutMax[5] >> + fCalibrateOutMax[6]; } else if (token == "calibrateoutdebuginfo") { // wyjście z info o przebiegu kalibracji Parser.getTokens(1, false); - Parser >> Global::iCalibrateOutDebugInfo; + Parser >> iCalibrateOutDebugInfo; } else if (token == "pwm") { @@ -690,25 +521,25 @@ void Global::ConfigParse(cParser &Parser) Parser.getTokens(2, false); int pwm_out, pwm_no; Parser >> pwm_out >> pwm_no; - Global::iPoKeysPWM[pwm_out] = pwm_no; + iPoKeysPWM[pwm_out] = pwm_no; } else if (token == "brakestep") { // krok zmiany hamulca dla klawiszy [Num3] i [Num9] Parser.getTokens(1, false); - Parser >> Global::fBrakeStep; + Parser >> fBrakeStep; } else if (token == "joinduplicatedevents") { // czy grupować eventy o tych samych nazwach Parser.getTokens(); - Parser >> Global::bJoinEvents; + Parser >> bJoinEvents; } else if (token == "hiddenevents") { // czy łączyć eventy z torami poprzez nazwę toru Parser.getTokens(1, false); - Parser >> Global::iHiddenEvents; + Parser >> iHiddenEvents; } else if (token == "pause") { @@ -721,20 +552,20 @@ void Global::ConfigParse(cParser &Parser) { // domyślny język - http://tools.ietf.org/html/bcp47 Parser.getTokens(1, false); - Parser >> Global::asLang; + Parser >> asLang; } else if( token == "uitextcolor" ) { // color of the ui text. NOTE: will be obsolete once the real ui is in place Parser.getTokens( 3, false ); Parser - >> Global::UITextColor.x - >> Global::UITextColor.y - >> Global::UITextColor.z; - Global::UITextColor.x = clamp( Global::UITextColor.x, 0.0f, 255.0f ); - Global::UITextColor.y = clamp( Global::UITextColor.y, 0.0f, 255.0f ); - Global::UITextColor.z = clamp( Global::UITextColor.z, 0.0f, 255.0f ); - Global::UITextColor = Global::UITextColor / 255.0f; - Global::UITextColor.w = 1.0f; + >> UITextColor.x + >> UITextColor.y + >> UITextColor.z; + UITextColor.x = clamp( UITextColor.x, 0.0f, 255.0f ); + UITextColor.y = clamp( UITextColor.y, 0.0f, 255.0f ); + UITextColor.z = clamp( UITextColor.z, 0.0f, 255.0f ); + UITextColor = UITextColor / 255.0f; + UITextColor.w = 1.0f; } else if (token == "pyscreenrendererpriority") { @@ -746,7 +577,7 @@ void Global::ConfigParse(cParser &Parser) else if( token == "input.gamepad" ) { // czy grupować eventy o tych samych nazwach Parser.getTokens(); - Parser >> Global::InputGamepad; + Parser >> InputGamepad; } // maciek001: ustawienia MWD else if (token == "mwdmasterenable") { // główne włączenie maszyny! @@ -890,299 +721,3 @@ void Global::ConfigParse(cParser &Parser) } */ } - -void Global::InitKeys() -{ - Keys[k_IncMainCtrl] = GLFW_KEY_KP_ADD; - Keys[k_IncMainCtrlFAST] = GLFW_KEY_KP_ADD; - Keys[k_DecMainCtrl] = GLFW_KEY_KP_SUBTRACT; - Keys[k_DecMainCtrlFAST] = GLFW_KEY_KP_SUBTRACT; - Keys[k_IncScndCtrl] = GLFW_KEY_KP_DIVIDE; - Keys[k_IncScndCtrlFAST] = GLFW_KEY_KP_DIVIDE; - Keys[k_DecScndCtrl] = GLFW_KEY_KP_MULTIPLY; - Keys[k_DecScndCtrlFAST] = GLFW_KEY_KP_MULTIPLY; - - Keys[k_IncLocalBrakeLevel] = GLFW_KEY_KP_1; - Keys[k_DecLocalBrakeLevel] = GLFW_KEY_KP_7; - Keys[k_IncBrakeLevel] = GLFW_KEY_KP_3; - Keys[k_DecBrakeLevel] = GLFW_KEY_KP_9; - Keys[k_Releaser] = GLFW_KEY_KP_6; - Keys[k_EmergencyBrake] = GLFW_KEY_KP_0; - Keys[k_Brake3] = GLFW_KEY_KP_8; - Keys[k_Brake2] = GLFW_KEY_KP_5; - Keys[k_Brake1] = GLFW_KEY_KP_2; - Keys[k_Brake0] = GLFW_KEY_KP_4; - Keys[k_WaveBrake] = GLFW_KEY_KP_DECIMAL; - - Keys[k_AntiSlipping] = GLFW_KEY_KP_ENTER; - Keys[k_Sand] = 'S'; - Keys[k_Main] = 'M'; - Keys[k_Active] = 'W'; - Keys[k_Battery] = 'J'; - Keys[k_DirectionForward] = 'D'; - Keys[k_DirectionBackward] = 'R'; - Keys[k_Fuse] = 'N'; - Keys[k_Compressor] = 'C'; - Keys[k_Converter] = 'X'; - Keys[k_MaxCurrent] = 'F'; - Keys[k_CurrentAutoRelay] = 'G'; - Keys[k_BrakeProfile] = 'B'; - Keys[k_CurrentNext] = 'Z'; - - Keys[k_Czuwak] = ' '; - Keys[k_Horn] = 'A'; - Keys[k_Horn2] = 'A'; - - Keys[k_FailedEngineCutOff] = 'E'; - - Keys[k_MechUp] = GLFW_KEY_PAGE_UP; - Keys[k_MechDown] = GLFW_KEY_PAGE_DOWN; - Keys[k_MechLeft] = GLFW_KEY_LEFT; - Keys[k_MechRight] = GLFW_KEY_RIGHT; - Keys[k_MechForward] = GLFW_KEY_UP; - Keys[k_MechBackward] = GLFW_KEY_DOWN; - - Keys[k_CabForward] = GLFW_KEY_HOME; - Keys[k_CabBackward] = GLFW_KEY_END; - - Keys[k_Couple] = GLFW_KEY_INSERT; - Keys[k_DeCouple] = GLFW_KEY_DELETE; - - Keys[k_ProgramQuit] = GLFW_KEY_F10; - Keys[k_ProgramHelp] = GLFW_KEY_F1; - Keys[k_WalkMode] = GLFW_KEY_F5; - - Keys[k_OpenLeft] = ','; - Keys[k_OpenRight] = '.'; - Keys[k_CloseLeft] = ','; - Keys[k_CloseRight] = '.'; - Keys[k_DepartureSignal] = '/'; - - // Winger 160204 - obsluga pantografow - Keys[k_PantFrontUp] = 'P'; // Ra: zamieniony przedni z tylnym - Keys[k_PantFrontDown] = 'P'; - Keys[k_PantRearUp] = 'O'; - Keys[k_PantRearDown] = 'O'; - // Winger 020304 - ogrzewanie - Keys[k_Heating] = 'H'; - // headlights - Keys[k_LeftSign] = 'Y'; - Keys[k_UpperSign] = 'U'; - Keys[k_RightSign] = 'I'; - Keys[k_DimHeadlights] = 'L'; - // tail lights - Keys[k_EndSign] = 'T'; - - Keys[k_SmallCompressor] = 'V'; - Keys[k_StLinOff] = 'L'; - // ABu 090305 - przyciski uniwersalne, do roznych bajerow :) - Keys[k_Univ1] = '['; - Keys[k_Univ2] = ']'; - Keys[k_Univ3] = ';'; - Keys[k_Univ4] = '\''; -} - -/* -vector3 Global::GetCameraPosition() -{ - return pCameraPosition; -} -*/ -void Global::SetCameraPosition(vector3 pNewCameraPosition) -{ - pCameraPosition = pNewCameraPosition; -} - -void Global::TrainDelete(TDynamicObject *d) -{ // usunięcie pojazdu prowadzonego przez użytkownika - if (pWorld) - pWorld->TrainDelete(d); -}; - -//--------------------------------------------------------------------------- - -TTranscripts::TTranscripts() -{ -/* - iCount = 0; // brak linijek do wyświetlenia - iStart = 0; // wypełniać od linijki 0 - for (int i = 0; i < MAX_TRANSCRIPTS; ++i) - { // to do konstruktora można by dać - aLines[i].fHide = -1.0; // wolna pozycja (czas symulacji, 360.0 to doba) - aLines[i].iNext = -1; // nie ma kolejnej - } -*/ - fRefreshTime = 360.0; // wartośc zaporowa -}; -TTranscripts::~TTranscripts(){}; - -void TTranscripts::AddLine(std::string const &txt, float show, float hide, bool it) -{ // dodanie linii do tabeli, (show) i (hide) w [s] od aktualnego czasu - if (show == hide) - return; // komentarz jest ignorowany - show = Global::fTimeAngleDeg + show / 240.0; // jeśli doba to 360, to 1s będzie równe 1/240 - hide = Global::fTimeAngleDeg + hide / 240.0; - - TTranscript transcript; - transcript.asText = txt; - transcript.fShow = show; - transcript.fHide = hide; - transcript.bItalic = it; - aLines.emplace_back( transcript ); - // set the next refresh time while at it - // TODO, TBD: sort the transcript lines? in theory, they should be coming arranged in the right order anyway - // short of cases with multiple sounds overleaping - fRefreshTime = aLines.front().fHide; -/* - int i = iStart, j, k; // od czegoś trzeba zacząć - while ((aLines[i].iNext >= 0) ? (aLines[aLines[i].iNext].fShow <= show) : - false) // póki nie koniec i wcześniej puszczane - i = aLines[i].iNext; // przejście do kolejnej linijki -*/ -/* - //(i) wskazuje na linię, po której należy wstawić dany tekst, chyba że - while (txt ? *txt : false) - for (j = 0; j < MAX_TRANSCRIPTS; ++j) - if (aLines[j].fHide < 0.0) - { // znaleziony pierwszy wolny - aLines[j].iNext = aLines[i].iNext; // dotychczasowy następny będzie za nowym - if (aLines[iStart].fHide < 0.0) // jeśli tablica jest pusta - iStart = j; // fHide trzeba sprawdzić przed ewentualnym nadpisaniem, gdy i=j=0 - else - aLines[i].iNext = j; // a nowy będzie za tamtym wcześniejszym - aLines[j].fShow = show; // wyświetlać od - aLines[j].fHide = hide; // wyświetlać do - aLines[j].bItalic = it; - aLines[j].asText = std::string(txt); // bez sensu, wystarczyłby wskaźnik - if ((k = aLines[j].asText.find("|")) != std::string::npos) - { // jak jest podział linijki na wiersze - aLines[j].asText = aLines[j].asText.substr(0, k - 1); - txt += k; - i = j; // kolejna linijka dopisywana będzie na koniec właśnie dodanej - } - else - txt = NULL; // koniec dodawania - if (fRefreshTime > show) // jeśli odświeżacz ustawiony jest na później - fRefreshTime = show; // to odświeżyć wcześniej - break; // więcej już nic - } -*/ -}; -void TTranscripts::Add(std::string const &txt, bool backgorund) -{ // dodanie tekstów, długość dźwięku, czy istotne - if (true == txt.empty()) - return; // pusty tekst - - std::string asciitext{ txt }; win1250_to_ascii( asciitext ); // TODO: launch relevant conversion table based on language - cParser parser( asciitext ); - while( true == parser.getTokens( 3, false, "[]\n" ) ) { - - float begin, end; - std::string transcript; - parser - >> begin - >> end - >> transcript; - AddLine( transcript, 0.10 * begin, 0.12 * end, false ); - } - // try to handle malformed(?) cases with no show/hide times - std::string transcript; parser >> transcript; - while( false == transcript.empty() ) { - -// WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); - AddLine( transcript, 0.0, 0.12 * transcript.size(), false ); - transcript = ""; parser >> transcript; - } -}; -void TTranscripts::Update() -{ // usuwanie niepotrzebnych (nie częściej niż 10 razy na sekundę) - if( Global::fTimeAngleDeg < fRefreshTime ) - return; // nie czas jeszcze na zmiany - // czas odświeżenia można ustalić wg tabelki, kiedy coś się w niej zmienia - // fRefreshTime = Global::fTimeAngleDeg + 360.0; // wartość zaporowa - - while( ( false == aLines.empty() ) - && ( Global::fTimeAngleDeg >= aLines.front().fHide ) ) { - // remove expired lines - aLines.pop_front(); - } - // update next refresh time - if( false == aLines.empty() ) { fRefreshTime = aLines.front().fHide; } - else { fRefreshTime = 360.0f; } -/* - int i = iStart, j = -1; // od czegoś trzeba zacząć - bool change = false; // czy zmieniać napisy? - do - { - if (aLines[i].fHide >= 0.0) // o ile aktywne - if (aLines[i].fHide < Global::fTimeAngleDeg) - { // gdy czas wyświetlania upłynął - aLines[i].fHide = -1.0; // teraz będzie wolną pozycją - if (i == iStart) - iStart = aLines[i].iNext >= 0 ? aLines[i].iNext : 0; // przestawienie pierwszego - else if (j >= 0) - aLines[j].iNext = aLines[i].iNext; // usunięcie ze środka - change = true; - } - else - { // gdy ma być pokazane - if (aLines[i].fShow > Global::fTimeAngleDeg) // będzie pokazane w przyszłości - if (fRefreshTime > aLines[i].fShow) // a nie ma nic wcześniej - fRefreshTime = aLines[i].fShow; - if (fRefreshTime > aLines[i].fHide) - fRefreshTime = aLines[i].fHide; - } - // można by jeszcze wykrywać, które nowe mają być pokazane - j = i; - i = aLines[i].iNext; // kolejna linijka - } while (i >= 0); // póki po tablicy - change = true; // bo na razie nie ma warunku, że coś się dodało - if (change) - { // aktualizacja linijek ekranowych - i = iStart; - j = -1; - do - { - if (aLines[i].fHide > 0.0) // jeśli nie ukryte - if (aLines[i].fShow < Global::fTimeAngleDeg) // to dodanie linijki do wyświetlania - if (j < 5 - 1) // ograniczona liczba linijek - Global::asTranscript[++j] = aLines[i].asText; // skopiowanie tekstu - i = aLines[i].iNext; // kolejna linijka - } while (i >= 0); // póki po tablicy - for (++j; j < 5; ++j) - Global::asTranscript[j] = ""; // i czyszczenie nieużywanych linijek - } -*/ -}; - -// Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów -char bezogonkowo[] = "E?,?\"_++?%Sstzz" - " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" - "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" - "raaaalccceeeeiiddnnoooo-ruuuuyt?"; - -std::string Global::Bezogonkow(std::string str, bool _) -{ // wycięcie liter z ogonkami, bo OpenGL nie umie wyświetlić - for (unsigned int i = 1; i < str.length(); ++i) - if (str[i] & 0x80) - str[i] = bezogonkowo[str[i] & 0x7F]; - else if (str[i] < ' ') // znaki sterujące nie są obsługiwane - str[i] = ' '; - else if (_) - if (str[i] == '_') // nazwy stacji nie mogą zawierać spacji - str[i] = ' '; // więc trzeba wyświetlać inaczej - return str; -}; - -double Global::Min0RSpeed(double vel1, double vel2) -{ // rozszerzenie funkcji Min0R o wartości -1.0 - if (vel1 == -1.0) - { - vel1 = std::numeric_limits::max(); - } - if (vel2 == -1.0) - { - vel2 = std::numeric_limits::max(); - } - return std::min(vel1, vel2); -}; diff --git a/Globals.h b/Globals.h index 806e2585..27575025 100644 --- a/Globals.h +++ b/Globals.h @@ -9,301 +9,186 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include - -#include "renderer.h" +#include "classes.h" #include "dumb3d.h" +#include "float3d.h" +#include "light.h" +#include "utilities.h" -// definicje klawiszy -const int k_IncMainCtrl = 0; //[Num+] -const int k_IncMainCtrlFAST = 1; //[Num+] [Shift] -const int k_DecMainCtrl = 2; //[Num-] -const int k_DecMainCtrlFAST = 3; //[Num-] [Shift] -const int k_IncScndCtrl = 4; //[Num/] -const int k_IncScndCtrlFAST = 5; -const int k_DecScndCtrl = 6; -const int k_DecScndCtrlFAST = 7; -const int k_IncLocalBrakeLevel = 8; -const int k_IncLocalBrakeLevelFAST = 9; -const int k_DecLocalBrakeLevel = 10; -const int k_DecLocalBrakeLevelFAST = 11; -const int k_IncBrakeLevel = 12; -const int k_DecBrakeLevel = 13; -const int k_Releaser = 14; -const int k_EmergencyBrake = 15; -const int k_Brake3 = 16; -const int k_Brake2 = 17; -const int k_Brake1 = 18; -const int k_Brake0 = 19; -const int k_WaveBrake = 20; -const int k_AntiSlipping = 21; -const int k_Sand = 22; - -const int k_Main = 23; -const int k_DirectionForward = 24; -const int k_DirectionBackward = 25; - -const int k_Fuse = 26; -const int k_Compressor = 27; -const int k_Converter = 28; -const int k_MaxCurrent = 29; -const int k_CurrentAutoRelay = 30; -const int k_BrakeProfile = 31; - -const int k_Czuwak = 32; -const int k_Horn = 33; -const int k_Horn2 = 34; - -const int k_FailedEngineCutOff = 35; - -const int k_MechUp = 36; -const int k_MechDown = 37; -const int k_MechLeft = 38; -const int k_MechRight = 39; -const int k_MechForward = 40; -const int k_MechBackward = 41; - -const int k_CabForward = 42; -const int k_CabBackward = 43; - -const int k_Couple = 44; -const int k_DeCouple = 45; - -const int k_ProgramQuit = 46; -// const int k_ProgramPause= 47; -const int k_ProgramHelp = 48; -// NBMX -const int k_OpenLeft = 49; -const int k_OpenRight = 50; -const int k_CloseLeft = 51; -const int k_CloseRight = 52; -const int k_DepartureSignal = 53; -// NBMX -const int k_PantFrontUp = 54; -const int k_PantRearUp = 55; -const int k_PantFrontDown = 56; -const int k_PantRearDown = 57; - -const int k_Heating = 58; - -// const int k_FreeFlyMode= 59; - -const int k_LeftSign = 60; -const int k_UpperSign = 61; -const int k_RightSign = 62; - -const int k_SmallCompressor = 63; - -const int k_StLinOff = 64; - -const int k_CurrentNext = 65; - -const int k_Univ1 = 66; -const int k_Univ2 = 67; -const int k_Univ3 = 68; -const int k_Univ4 = 69; -const int k_EndSign = 70; - -const int k_Active = 71; -// Winger 020304 -const int k_Battery = 72; -const int k_WalkMode = 73; -int const k_DimHeadlights = 74; -const int MaxKeys = 75; - -class TTranscript -{ // klasa obsługująca linijkę napisu do dźwięku - public: - float fShow; // czas pokazania - float fHide; // czas ukrycia/usunięcia - std::string asText; // tekst gotowy do wyświetlenia (usunięte znaczniki czasu) - bool bItalic; // czy kursywa (dźwięk nieistotny dla prowadzącego) -}; - -class TTranscripts -{ // klasa obsługująca napisy do dźwięków -public: - std::deque aLines; - -private: - float fRefreshTime; - - public: - TTranscripts(); - ~TTranscripts(); - void AddLine(std::string const &txt, float show, float hide, bool it); - // dodanie tekstów, długość dźwięku, czy istotne - void Add(std::string const &txt, bool background = false); - // usuwanie niepotrzebnych (ok. 10 razy na sekundę) - void Update(); -}; - -class Global { - -public: -// methods - static void LoadIniFile(std::string asFileName); - static void ConfigParse( cParser &parser ); - static void InitKeys(); - inline static Math3D::vector3 GetCameraPosition() { return pCameraPosition; }; - static void SetCameraPosition(Math3D::vector3 pNewCameraPosition); - static void TrainDelete(TDynamicObject *d); - static std::string Bezogonkow(std::string str, bool _ = false); - static double Min0RSpeed(double vel1, double vel2); - +struct global_settings { // members - static int Keys[MaxKeys]; - static bool RealisticControlMode; // controls ability to steer the vehicle from outside views - static Math3D::vector3 pCameraPosition; // pozycja kamery w świecie - static Math3D::vector3 DebugCameraPosition; // pozycja kamery w świecie - static std::vector FreeCameraInit; // pozycje kamery - static std::vector FreeCameraInitAngle; - static int iWindowWidth; - static int iWindowHeight; - static float fDistanceFactor; - static bool bFullScreen; - static bool VSync; - static bool bFreeFly; - static bool bWireFrame; - // McZapkie-131202 - static bool bAdjustScreenFreq; - static bool bEnableTraction; - static bool bLoadTraction; - static float fFriction; - static bool bLiveTraction; - static float Global::fMouseXScale; - static float Global::fMouseYScale; - static std::string szDefaultExt; - static std::string SceneryFile; - static std::string AppName; - static std::string asCurrentSceneryPath; - static std::string asCurrentTexturePath; - static std::string asCurrentDynamicPath; - static int iWriteLogEnabled; // maska bitowa: 1-zapis do pliku, 2-okienko - static bool MultipleLogs; - static unsigned int DisabledLogTypes; - // McZapkie-170602: zewnetrzna definicja pojazdu uzytkownika - static std::string asHumanCtrlVehicle; - // world environment - static float Overcast; - static double fFogStart; - static double fFogEnd; - static std::string Season; // season of the year, based on simulation date - static std::string Weather; // current weather - - // TODO: put these things in the renderer - static float BaseDrawRange; - static opengl_light DayLight; - static int DynamicLightCount; - static bool ScaleSpecularValues; - static bool BasicRenderer; - static bool RenderShadows; - static struct shadowtune_t { - unsigned int map_size; - float width; - float depth; - float distance; + // data items + // TODO: take these out of the settings + GLFWwindow *window{ nullptr }; + bool shiftState{ false }; //m7todo: brzydko + bool ctrlState{ false }; + std::mt19937 random_engine{ std::mt19937( static_cast( std::time( NULL ) ) ) }; + TDynamicObject *changeDynObj{ nullptr };// info o zmianie pojazdu + TWorld *pWorld{ nullptr }; // wskaźnik na świat do usuwania pojazdów + TCamera *pCamera{ nullptr }; // parametry kamery + Math3D::vector3 pCameraPosition; // pozycja kamery w świecie + Math3D::vector3 DebugCameraPosition; // pozycja kamery w świecie + std::vector FreeCameraInit; // pozycje kamery + std::vector FreeCameraInitAngle; + int iCameraLast{ -1 }; + int iSlowMotion{ 0 }; // info o malym FPS: 0-OK, 1-wyłączyć multisampling, 3-promień 1.5km, 7-1km + basic_light DayLight; + float SunAngle{ 0.f }; // angle of the sun relative to horizon + double fLuminance{ 1.0 }; // jasność światła do automatycznego zapalania + double fTimeAngleDeg{ 0.0 }; // godzina w postaci kąta + float fClockAngleDeg[ 6 ]; // kąty obrotu cylindrów dla zegara cyfrowego + std::string LastGLError; + float ZoomFactor{ 1.f }; // determines current camera zoom level. TODO: move it to the renderer + bool CabWindowOpen{ false }; // controls sound attenuation between cab and outside + bool ControlPicking{ false }; // indicates controls pick mode is active + bool DLFont{ false }; // switch indicating presence of basic font + bool bActive{ true }; // czy jest aktywnym oknem + int iPause{ 0 }; // globalna pauza ruchu: b0=start,b1=klawisz,b2=tło,b3=lagi,b4=wczytywanie + // settings + // filesystem + bool bLoadTraction{ true }; + std::string szTexturesTGA{ ".tga" }; // lista tekstur od TGA + std::string szTexturesDDS{ ".dds" }; // lista tekstur od DDS + std::string szDefaultExt{ szTexturesDDS }; + std::string asCurrentSceneryPath{ "scenery/" }; + std::string asCurrentTexturePath{ szTexturePath }; + std::string asCurrentDynamicPath; + std::string SceneryFile{ "td.scn" }; + std::string asHumanCtrlVehicle{ "EU07-424" }; + int iConvertModels{ 0 }; // tworzenie plików binarnych + // logs + int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów + bool MultipleLogs{ false }; + unsigned int DisabledLogTypes{ 0 }; + bool bMWDdebugEnable{ false }; // włącz dodawanie do logu + int iMWDDebugMode{ 0 }; // co ma wyświetlać w logu + // simulation + bool RealisticControlMode{ false }; // controls ability to steer the vehicle from outside views + bool bFreeFly{ false }; + bool bEnableTraction{ true }; + float fFriction{ 1.f }; // mnożnik tarcia - KURS90 + bool bLiveTraction{ true }; + float Overcast{ 0.1f }; // NOTE: all this weather stuff should be moved elsewhere + GLfloat FogColor[ 3 ] = { 0.6f, 0.7f, 0.8f }; + double fFogStart{ 1700 }; + double fFogEnd{ 2000 }; + std::string Season; // season of the year, based on simulation date + std::string Weather{ "clear" }; // current weather + bool FullPhysics{ true }; // full calculations performed for each simulation step + bool bnewAirCouplers{ true }; + double fMoveLight{ -1 }; // numer dnia w roku albo -1 + bool FakeLight{ false }; // toggle between fixed and dynamic daylight + double fTimeSpeed{ 1.0 }; // przyspieszenie czasu, zmienna do testów + double fLatitudeDeg{ 52.0 }; // szerokość geograficzna + bool bInactivePause{ true }; // automatyczna pauza, gdy okno nieaktywne + int iSlowMotionMask{ -1 }; // maska wyłączanych właściwości + bool bHideConsole{ false }; // hunter-271211: ukrywanie konsoli + bool bRollFix{ true }; // czy wykonać przeliczanie przechyłki + bool bJoinEvents{ false }; // czy grupować eventy o tych samych nazwach + int iHiddenEvents{ 1 }; // czy łączyć eventy z torami poprzez nazwę toru + // ui + int iTextMode{ 0 }; // tryb pracy wyświetlacza tekstowego + int iScreenMode[ 12 ] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // numer ekranu wyświetlacza tekstowego + float4 UITextColor{ float4( 225.f / 255.f, 225.f / 255.f, 225.f / 255.f, 1.f ) }; // base color of UI text + std::string asLang{ "pl" }; // domyślny język - http://tools.ietf.org/html/bcp47 + // gfx + int iWindowWidth{ 800 }; + int iWindowHeight{ 600 }; + float fDistanceFactor{ iWindowHeight / 768.f }; // baza do przeliczania odległości dla LoD + bool bFullScreen{ false }; + bool VSync{ false }; + bool bWireFrame{ false }; + bool bAdjustScreenFreq{ true }; + float BaseDrawRange{ 2500.f }; + int DynamicLightCount{ 3 }; + bool ScaleSpecularValues{ true }; + bool BasicRenderer{ false }; + bool RenderShadows{ true }; + struct shadowtune_t { + unsigned int map_size{ 2048 }; + float width{ 250.f }; // no longer used + float depth{ 250.f }; + float distance{ 500.f }; // no longer used } shadowtune; - static bool bUseVBO; // czy jest VBO w karcie graficznej - static float AnisotropicFiltering; // requested level of anisotropic filtering. TODO: move it to renderer object - static int ScreenWidth; // current window dimensions. TODO: move it to renderer - static int ScreenHeight; - static float ZoomFactor; // determines current camera zoom level. TODO: move it to the renderer - static float FieldOfView; // vertical field of view for the camera. TODO: move it to the renderer - static GLint iMaxTextureSize; // maksymalny rozmiar tekstury - static int iMultisampling; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px - static bool bSmoothTraction; // wygładzanie drutów - static float SplineFidelity; // determines segment size during conversion of splines to geometry - static GLfloat FogColor[]; - static bool ResourceSweep; // gfx resource garbage collection - static bool ResourceMove; // gfx resources are moved between cpu and gpu side instead of sending a copy - // sound renderer variables - static bool bSoundEnabled; - static float AudioVolume; - static std::string AudioRenderer; + bool bUseVBO{ true }; // czy jest VBO w karcie graficznej (czy użyć) + float AnisotropicFiltering{ 8.f }; // requested level of anisotropic filtering. TODO: move it to renderer object + float FieldOfView{ 45.f }; // vertical field of view for the camera. TODO: move it to the renderer + GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury + int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px + bool bSmoothTraction{ true }; // wygładzanie drutów starym sposobem + float SplineFidelity{ 1.f }; // determines segment size during conversion of splines to geometry + bool ResourceSweep{ true }; // gfx resource garbage collection + bool ResourceMove{ false }; // gfx resources are moved between cpu and gpu side instead of sending a copy + std::string asSky{ "1" }; + bool bGlutFont{ false }; // czy tekst generowany przez GLUT32.DLL + double fFpsAverage{ 20.0 }; // oczekiwana wartosć FPS + double fFpsDeviation{ 5.0 }; // odchylenie standardowe FPS + double fFpsMin{ 30.0 }; // dolna granica FPS, przy której promień scenerii będzie zmniejszany + double fFpsMax{ 65.0 }; // górna granica FPS, przy której promień scenerii będzie zwiększany + // audio + bool bSoundEnabled{ true }; + float AudioVolume{ 1.25f }; + std::string AudioRenderer; + // input + float fMouseXScale{ 1.5f }; + float fMouseYScale{ 0.2f }; + int iFeedbackMode{ 1 }; // tryb pracy informacji zwrotnej + int iFeedbackPort{ 0 }; // dodatkowy adres dla informacji zwrotnych + bool InputGamepad{ true }; // whether gamepad support is enabled + bool InputMouse{ true }; // whether control pick mode can be activated + double fBrakeStep{ 1.0 }; // krok zmiany hamulca dla klawiszy [Num3] i [Num9] + // parametry kalibracyjne wejść z pulpitu + double fCalibrateIn[ 6 ][ 6 ] = { + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 } }; + // parametry kalibracyjne wyjść dla pulpitu + double fCalibrateOut[ 7 ][ 6 ] = { + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 }, + { 0, 1, 0, 0, 0, 0 } }; + // wartości maksymalne wyjść dla pulpitu + double fCalibrateOutMax[ 7 ] = { + 0, 0, 0, 0, 0, 0, 0 }; + int iCalibrateOutDebugInfo { -1 }; // numer wyjścia kalibrowanego dla którego wyświetlać informacje podczas kalibracji + int iPoKeysPWM[ 7 ] = { 0, 1, 2, 3, 4, 5, 6 }; // numery wejść dla PWM + // maciek001: konfiguracja wstępna portu COM + bool bMWDmasterEnable { false };// główne włączenie portu! + std::string sMWDPortId { "COM1" }; // nazwa portu z którego korzystamy + unsigned long int iMWDBaudrate{ 9600 }; // prędkość transmisji danych + bool bMWDInputEnable { false }; // włącz wejścia + bool bMWDBreakEnable { false }; // włącz wejścia analogowe + // wartość max potencjometru, wartość min potencjometru, rozdzielczość (max. wartość jaka może być) + double fMWDAnalogInCalib[ 4 ][ 2 ] = { + { 0, 1023 }, + { 0, 1023 }, + { 0, 1023 }, + { 0, 1023 } }; + double fMWDzg[ 2 ] = { 0.9, 1023 }; + double fMWDpg[ 2 ] = { 0.8, 1023 }; + double fMWDph[ 2 ] = { 0.6, 1023 }; + double fMWDvolt[ 2 ] = { 4000, 1023 }; + double fMWDamp[ 2 ] = { 800, 1023 }; + double fMWDlowVolt[ 2 ] = { 150, 1023 }; + int iMWDdivider { 5 }; + // multiplayer + int iMultiplayer{ 0 }; // blokada działania niektórych eventów na rzecz kominikacji + // other + std::string AppName{ "EU07" }; + std::string asVersion{ "couldn't retrieve version string" }; // z opisem - static bool FullPhysics; // full calculations performed for each simulation step - static int iSlowMotion; - static TDynamicObject *changeDynObj; - static double ABuDebug; - static std::string asSky; - static bool bnewAirCouplers; - // Ra: nowe zmienne globalne - static std::string LastGLError; - static int iFeedbackMode; // tryb pracy informacji zwrotnej - static int iFeedbackPort; // dodatkowy adres dla informacji zwrotnych - static bool InputGamepad; // whether gamepad support is enabled - static double fLuminance; // jasność światła do automatycznego zapalania - static float SunAngle; // angle of the sun relative to horizon - static int iMultiplayer; // blokada działania niektórych eventów na rzecz kominikacji - static GLFWwindow *window; - static bool shiftState; //m7todo: brzydko - static bool ctrlState; - static bool CabWindowOpen; // controls sound attenuation between cab and outside - static int iCameraLast; - static std::string asVersion; // z opisem - static bool ControlPicking; // indicates controls pick mode is active - static bool InputMouse; // whether control pick mode can be activated - static int iTextMode; // tryb pracy wyświetlacza tekstowego - static int iScreenMode[12]; // numer ekranu wyświetlacza tekstowego - static double fMoveLight; // numer dnia w roku albo -1 - static bool FakeLight; // toggle between fixed and dynamic daylight - static double fTimeSpeed; // przyspieszenie czasu, zmienna do testów - static double fTimeAngleDeg; // godzina w postaci kąta - static float fClockAngleDeg[6]; // kąty obrotu cylindrów dla zegara cyfrowego - static double fLatitudeDeg; // szerokość geograficzna - static std::string szTexturesTGA; // lista tekstur od TGA - static std::string szTexturesDDS; // lista tekstur od DDS - static bool DLFont; // switch indicating presence of basic font - static bool bGlutFont; // tekst generowany przez GLUT - static int iPause; // globalna pauza ruchu: b0=start,b1=klawisz,b2=tło,b3=lagi,b4=wczytywanie - static bool bActive; // czy jest aktywnym oknem - static int iConvertModels; // tworzenie plików binarnych - static bool bInactivePause; // automatyczna pauza, gdy okno nieaktywne - static int iSlowMotionMask; // maska wyłączanych właściwości - static bool bHideConsole; // hunter-271211: ukrywanie konsoli - - static TWorld *pWorld; // wskaźnik na świat do usuwania pojazdów - static bool bRollFix; // czy wykonać przeliczanie przechyłki - static double fFpsAverage; // oczekiwana wartosć FPS - static double fFpsDeviation; // odchylenie standardowe FPS - static double fFpsMin; // dolna granica FPS, przy której promień scenerii będzie zmniejszany - static double fFpsMax; // górna granica FPS, przy której promień scenerii będzie zwiększany - static TCamera *pCamera; // parametry kamery - static double fCalibrateIn[6][6]; // parametry kalibracyjne wejść z pulpitu - static double fCalibrateOut[7][6]; // parametry kalibracyjne wyjść dla pulpitu - static double fCalibrateOutMax[7]; // wartości maksymalne wyjść dla pulpitu - static int iCalibrateOutDebugInfo; // numer wyjścia kalibrowanego dla którego wyświetlać - // informacje podczas kalibracji - static double fBrakeStep; // krok zmiany hamulca dla klawiszy [Num3] i [Num9] - static bool bJoinEvents; // czy grupować eventy o tych samych nazwach - static TTranscripts tranTexts; // obiekt obsługujący stenogramy dźwięków na ekranie - static float4 UITextColor; // base color of UI text - static std::string asLang; // domyślny język - http://tools.ietf.org/html/bcp47 - static int iHiddenEvents; // czy łączyć eventy z torami poprzez nazwę toru -/* - static TTextSound *tsRadioBusy[10]; // zajętość kanałów radiowych (wskaźnik na odgrywany dźwięk) -*/ - static int iPoKeysPWM[7]; // numery wejść dla PWM - - //randomizacja - static std::mt19937 random_engine; - - // maciek001: zmienne dla MWD - static bool bMWDmasterEnable; // główne włączenie portu COM - static bool bMWDdebugEnable; // logowanie pracy - static int iMWDDebugMode; - static std::string sMWDPortId; // nazwa portu COM - static unsigned long int iMWDBaudrate; // prędkość transmisji - static bool bMWDInputEnable; // włącz wejścia - static bool bMWDBreakEnable; // włącz wejścia analogowe (hamulce) - static double fMWDAnalogInCalib[4][2]; // ustawienia kranów hamulca zespolonego i dodatkowego - min i max - static double fMWDzg[2]; // max wartość wskazywana i max wartość generowana (rozdzielczość) - static double fMWDpg[2]; - static double fMWDph[2]; - static double fMWDvolt[2]; - static double fMWDamp[2]; - static double fMWDlowVolt[2]; - static int iMWDdivider; +// methods + void LoadIniFile( std::string asFileName ); + void ConfigParse( cParser &parser ); }; + +extern global_settings Global; + //--------------------------------------------------------------------------- diff --git a/Logs.cpp b/Logs.cpp index 5453a510..612d489f 100644 --- a/Logs.cpp +++ b/Logs.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "Logs.h" #include "Globals.h" +#include "utilities.h" std::ofstream output; // standardowy "log.txt", można go wyłączyć std::ofstream errors; // lista błędów "errors.txt", zawsze działa @@ -38,25 +39,25 @@ std::string filename_date() { std::string filename_scenery() { - auto extension = Global::SceneryFile.rfind( '.' ); + auto extension = Global.SceneryFile.rfind( '.' ); if( extension != std::string::npos ) { - return Global::SceneryFile.substr( 0, extension ); + return Global.SceneryFile.substr( 0, extension ); } else { - return Global::SceneryFile; + return Global.SceneryFile; } } void WriteLog( const char *str, logtype const Type ) { if( str == nullptr ) { return; } - if( true == TestFlag( Global::DisabledLogTypes, Type ) ) { return; } + if( true == TestFlag( Global.DisabledLogTypes, Type ) ) { return; } - if (Global::iWriteLogEnabled & 1) { + if (Global.iWriteLogEnabled & 1) { if( !output.is_open() ) { std::string const filename = - ( Global::MultipleLogs ? + ( Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt" ); output.open( filename, std::ios::trunc ); @@ -65,7 +66,7 @@ void WriteLog( const char *str, logtype const Type ) { output.flush(); } - if( Global::iWriteLogEnabled & 2 ) { + if( Global.iWriteLogEnabled & 2 ) { // hunter-271211: pisanie do konsoli tylko, gdy nie jest ukrywana SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN | FOREGROUND_INTENSITY ); DWORD wr = 0; @@ -78,16 +79,16 @@ void WriteLog( const char *str, logtype const Type ) { void ErrorLog( const char *str, logtype const Type ) { if( str == nullptr ) { return; } - if( true == TestFlag( Global::DisabledLogTypes, Type ) ) { return; } + if( true == TestFlag( Global.DisabledLogTypes, Type ) ) { return; } if (!errors.is_open()) { std::string const filename = - ( Global::MultipleLogs ? + ( Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt" ); errors.open( filename, std::ios::trunc ); - errors << "EU07.EXE " + Global::asVersion << "\n"; + errors << "EU07.EXE " + Global.asVersion << "\n"; } errors << str << "\n"; @@ -97,14 +98,14 @@ void ErrorLog( const char *str, logtype const Type ) { void Error(const std::string &asMessage, bool box) { // if (box) - // MessageBox(NULL, asMessage.c_str(), string("EU07 " + Global::asRelease).c_str(), MB_OK); + // MessageBox(NULL, asMessage.c_str(), string("EU07 " + Global.asRelease).c_str(), MB_OK); ErrorLog(asMessage.c_str()); } void Error(const char *&asMessage, bool box) { // if (box) - // MessageBox(NULL, asMessage, string("EU07 " + Global::asRelease).c_str(), MB_OK); + // MessageBox(NULL, asMessage, string("EU07 " + Global.asRelease).c_str(), MB_OK); ErrorLog(asMessage); WriteLog(asMessage); } @@ -123,12 +124,12 @@ void WriteLog(const std::string &str, logtype const Type ) void CommLog(const char *str) { // Ra: warunkowa rejestracja komunikatów WriteLog(str); - /* if (Global::iWriteLogEnabled & 4) + /* if (Global.iWriteLogEnabled & 4) { if (!comms.is_open()) { comms.open("comms.txt", std::ios::trunc); - comms << AnsiString("EU07.EXE " + Global::asRelease).c_str() << "\n"; + comms << AnsiString("EU07.EXE " + Global.asRelease).c_str() << "\n"; } if (str) comms << str; diff --git a/Logs.h b/Logs.h index 449e2c76..515baaa4 100644 --- a/Logs.h +++ b/Logs.h @@ -8,6 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #pragma once + #include enum logtype : unsigned int { diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1f865215..051798d9 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -9,11 +9,12 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "Mover.h" + +#include "Oerlikon_ESt.h" +#include "../utilities.h" #include "../globals.h" #include "../logs.h" -#include "Oerlikon_ESt.h" #include "../parser.h" -#include "mctools.h" //--------------------------------------------------------------------------- // Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. @@ -4260,23 +4261,13 @@ double TMoverParameters::TractionForce(double dt) case 2: { // automatic if( ( std::abs( Itot ) > RVentMinI ) && ( RList[ MainCtrlActualPos ].R > RVentCutOff ) ) { -/* - RventRot += ( RVentnmax * abs( Itot ) / ( ImaxLo * RList[ MainCtrlActualPos ].Bn ) - RventRot ) * RVentSpeed * dt; -*/ - RventRot = std::min( - RVentnmax, - RventRot - + ( RVentnmax - * std::abs( Itot ) - * std::min( 1.25, ( ( std::abs( Itot ) / NPoweredAxles ) / RVentMinI ) ) - / ImaxLo + + RventRot += + ( RVentnmax + * std::min( 1.0, ( ( Im / NPoweredAxles ) / RVentMinI ) ) + * Im / ImaxLo - RventRot ) - * RVentSpeed * dt ); -/* -RventRot = std::min( -RVentnmax, -RventRot + ( ( std::abs( Itot ) / ( RList[ MainCtrlActualPos ].Bn * RList[ MainCtrlActualPos ].Mn ) ) / RVentMinI ) * RVentSpeed * dt ); -*/ + * RVentSpeed * dt; } else if( ( DynamicBrakeType == dbrake_automatic ) && ( true == DynamicBrakeFlag ) ) { diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h index 62a64cee..a6b6f3d0 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/McZapkie/Oerlikon_ESt.h @@ -20,7 +20,6 @@ http://mozilla.org/MPL/2.0/. #include #include "hamulce.h" // Pascal unit #include "friction.h" // Pascal unit -#include "mctools.h" // Pascal unit /* (C) youBy diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index be9e1a01..e5f64025 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -16,7 +16,7 @@ Copyright (C) 2007-2014 Maciej Cierniak #include "hamulce.h" #include #include "Mover.h" -#include "usefull.h" +#include "utilities.h" //---FUNKCJE OGOLNE--- diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 805d53d3..c93cb184 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -35,7 +35,6 @@ Knorr/West EP - żeby był #pragma once #include "friction.h" // Pascal unit -#include "mctools.h" // Pascal unit static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca recznego lub pomocniczego*/ static int const MainBrakeMaxPos = 10; /*max. ilosc nastaw hamulca zasadniczego*/ diff --git a/MdlMngr.cpp b/MdlMngr.cpp index fa1f6236..41d95897 100644 --- a/MdlMngr.cpp +++ b/MdlMngr.cpp @@ -16,8 +16,9 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "MdlMngr.h" +#include "model3d.h" #include "Globals.h" -#include "McZapkie/mctools.h" +#include "utilities.h" // wczytanie modelu do kontenerka TModel3d * @@ -78,15 +79,15 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic) // - niebo animowane, ścieżka brana ze wpisu, tekstury nieokreślone // - wczytanie modelu animowanego - Init() - sprawdzić std::string buf; - std::string const buftp = Global::asCurrentTexturePath; // zapamiętanie aktualnej ścieżki do tekstur, + std::string const buftp = Global.asCurrentTexturePath; // zapamiętanie aktualnej ścieżki do tekstur, if( Name.find('\\') == std::string::npos ) { buf = "models\\" + Name; // Ra: było by lepiej katalog dodać w parserze if( Name.find( '/') != std::string::npos) { - Global::asCurrentTexturePath = Global::asCurrentTexturePath + Name; - Global::asCurrentTexturePath.erase(Global::asCurrentTexturePath.find("/") + 1, - Global::asCurrentTexturePath.length()); + Global.asCurrentTexturePath = Global.asCurrentTexturePath + Name; + Global.asCurrentTexturePath.erase(Global.asCurrentTexturePath.find("/") + 1, + Global.asCurrentTexturePath.length()); } } else @@ -95,10 +96,10 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic) if( Dynamic ) { // na razie tak, bo nie wiadomo, jaki może mieć wpływ na pozostałe modele if( Name.find( '/' ) != std::string::npos ) { // pobieranie tekstur z katalogu, w którym jest model - Global::asCurrentTexturePath = Global::asCurrentTexturePath + Name; - Global::asCurrentTexturePath.erase( - Global::asCurrentTexturePath.find( "/" ) + 1, - Global::asCurrentTexturePath.length() - 1 ); + Global.asCurrentTexturePath = Global.asCurrentTexturePath + Name; + Global.asCurrentTexturePath.erase( + Global.asCurrentTexturePath.find( "/" ) + 1, + Global.asCurrentTexturePath.length() - 1 ); } } } @@ -106,12 +107,12 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic) auto const lookup = m_modelsmap.find( buf ); if( lookup != m_modelsmap.end() ) { - Global::asCurrentTexturePath = buftp; + Global.asCurrentTexturePath = buftp; return ( m_models[ lookup->second ].Model.get() ); } auto model = LoadModel(buf, Dynamic); // model nie znaleziony, to wczytać - Global::asCurrentTexturePath = buftp; // odtworzenie ścieżki do tekstur + Global.asCurrentTexturePath = buftp; // odtworzenie ścieżki do tekstur return model; // NULL jeśli błąd }; diff --git a/MdlMngr.h b/MdlMngr.h index b8f53687..a70d60b5 100644 --- a/MdlMngr.h +++ b/MdlMngr.h @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #pragma once -#include "Model3d.h" +#include "classes.h" class TMdlContainer { friend class TModelsManager; diff --git a/MemCell.h b/MemCell.h index 061b75d9..adbbcbfd 100644 --- a/MemCell.h +++ b/MemCell.h @@ -11,7 +11,6 @@ http://mozilla.org/MPL/2.0/. #include "Classes.h" #include "scenenode.h" -#include "dumb3d.h" #include "names.h" class TMemCell : public editor::basic_node { diff --git a/Model3d.cpp b/Model3d.cpp index 80de2402..e988ba40 100644 --- a/Model3d.cpp +++ b/Model3d.cpp @@ -17,8 +17,7 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others #include "Globals.h" #include "logs.h" -#include "mczapkie/mctools.h" -#include "Usefull.h" +#include "utilities.h" #include "renderer.h" #include "Timer.h" #include "mtable.h" @@ -291,7 +290,7 @@ int TSubModel::Load( cParser &parser, TModel3d *Model, /*int Pos,*/ bool dynamic if (Opacity > 1.0f) Opacity *= 0.01f; // w 2013 był błąd i aby go obejść, trzeba było wpisać 10000.0 /* - if ((Global::iConvertModels & 1) == 0) // dla zgodności wstecz + if ((Global.iConvertModels & 1) == 0) // dla zgodności wstecz Opacity = 0.0; // wszystko idzie w przezroczyste albo zależnie od tekstury */ if (!parser.expectToken("map:")) @@ -331,7 +330,7 @@ int TSubModel::Load( cParser &parser, TModel3d *Model, /*int Pos,*/ bool dynamic { // jeśli tylko nazwa pliku, to dawać bieżącą ścieżkę do tekstur Name_Material(material); if( material.find_first_of( "/\\" ) == material.npos ) { - material.insert( 0, Global::asCurrentTexturePath ); + material.insert( 0, Global.asCurrentTexturePath ); } m_material = GfxRenderer.Fetch_Material( material ); // renderowanie w cyklu przezroczystych tylko jeśli: @@ -657,7 +656,7 @@ void TSubModel::InitialRotate(bool doit) // potomnych nie obracamy już, tylko ewentualnie optymalizujemy Child->InitialRotate( false ); } - else if (Global::iConvertModels & 2) { + else if (Global.iConvertModels & 2) { // optymalizacja jest opcjonalna if ((iFlags & 0xC000) == 0x8000) // o ile nie ma animacji { // jak nie ma potomnych, można wymnożyć przez transform i wyjedynkować go @@ -788,7 +787,7 @@ void TSubModel::SetRotateXYZ(float3 vNewAngles) iAnimOwner = iInstance; // zapamiętanie czyja jest animacja } -void TSubModel::SetRotateXYZ(vector3 vNewAngles) +void TSubModel::SetRotateXYZ( Math3D::vector3 vNewAngles) { // obrócenie submodelu o // podane kąty wokół osi // lokalnego układu @@ -808,7 +807,7 @@ void TSubModel::SetTranslate(float3 vNewTransVector) iAnimOwner = iInstance; // zapamiętanie czyja jest animacja } -void TSubModel::SetTranslate(vector3 vNewTransVector) +void TSubModel::SetTranslate( Math3D::vector3 vNewTransVector) { // przesunięcie submodelu (np. w kabinie) v_TransVector.x = vNewTransVector.x; v_TransVector.y = vNewTransVector.y; @@ -907,14 +906,14 @@ void TSubModel::RaAnimation(TAnimType a) glRotatef(simulation::Time.data().wMinute * 6.0 + simulation::Time.second() * 0.1, 0.0, 1.0, 0.0); break; case at_Hours: // godziny płynnie 12h/360° - glRotatef(2.0 * Global::fTimeAngleDeg, 0.0, 1.0, 0.0); + glRotatef(2.0 * Global.fTimeAngleDeg, 0.0, 1.0, 0.0); break; case at_Hours24: // godziny płynnie 24h/360° - glRotatef(Global::fTimeAngleDeg, 0.0, 1.0, 0.0); + glRotatef(Global.fTimeAngleDeg, 0.0, 1.0, 0.0); break; case at_Billboard: // obrót w pionie do kamery { - matrix4x4 mat; mat.OpenGL_Matrix( OpenGLMatrices.data_array( GL_MODELVIEW ) ); + Math3D::matrix4x4 mat; mat.OpenGL_Matrix( OpenGLMatrices.data_array( GL_MODELVIEW ) ); float3 gdzie = float3(mat[3][0], mat[3][1], mat[3][2]); // początek układu współrzędnych submodelu względem kamery glLoadIdentity(); // macierz jedynkowa glTranslatef(gdzie.x, gdzie.y, gdzie.z); // początek układu zostaje bez @@ -927,9 +926,9 @@ void TSubModel::RaAnimation(TAnimType a) glRotated(1.5 * std::sin(M_PI * simulation::Time.second() / 6.0), 0.0, 1.0, 0.0); break; case at_Sky: // animacja nieba - glRotated(Global::fLatitudeDeg, 1.0, 0.0, 0.0); // ustawienie osi OY na północ - // glRotatef(Global::fTimeAngleDeg,0.0,1.0,0.0); //obrót dobowy osi OX - glRotated(-fmod(Global::fTimeAngleDeg, 360.0), 0.0, 1.0, 0.0); // obrót dobowy osi OX + glRotated(Global.fLatitudeDeg, 1.0, 0.0, 0.0); // ustawienie osi OY na północ + // glRotatef(Global.fTimeAngleDeg,0.0,1.0,0.0); //obrót dobowy osi OX + glRotated(-fmod(Global.fTimeAngleDeg, 360.0), 0.0, 1.0, 0.0); // obrót dobowy osi OX break; case at_IK11: // ostatni element animacji szkieletowej (podudzie, stopa) glRotatef(v_Angles.z, 0.0f, 1.0f, 0.0f); // obrót względem osi pionowej (azymut) @@ -945,7 +944,7 @@ void TSubModel::RaAnimation(TAnimType a) if ((sm->pName[0]) >= '0') if ((sm->pName[0]) <= '5') // zegarek ma 6 cyfr maksymalnie sm->SetRotate(float3(0, 1, 0), - -Global::fClockAngleDeg[(sm->pName[0]) - '0']); + -Global.fClockAngleDeg[(sm->pName[0]) - '0']); } sm = sm->NextGet(); } while (sm); @@ -1633,7 +1632,7 @@ void TSubModel::BinInit(TSubModel *s, float4x4 *m, std::vector *t, if( materialindex < t->size() ) { m_materialname = t->at( materialindex ); if( m_materialname.find_last_of( "/\\" ) == std::string::npos ) { - m_materialname = Global::asCurrentTexturePath + m_materialname; + m_materialname = Global.asCurrentTexturePath + m_materialname; } m_material = GfxRenderer.Fetch_Material( m_materialname ); if( ( iFlags & 0x30 ) == 0 ) { @@ -1741,7 +1740,7 @@ void TModel3d::LoadFromTextFile(std::string const &FileName, bool dynamic) } // Ra: od wersji 334 przechylany jest cały model, a nie tylko pierwszy submodel // ale bujanie kabiny nadal używa bananów :( od 393 przywrócone, ale z dodatkowym warunkiem - if (Global::iConvertModels & 4) + if (Global.iConvertModels & 4) { // automatyczne banany czasem psuły przechylanie kabin... if (dynamic && Root) { @@ -1778,7 +1777,7 @@ void TModel3d::Init() std::size_t dataoffset = 0; Root->create_geometry( dataoffset, m_geometrybank ); } - if( ( Global::iConvertModels > 0 ) + if( ( Global.iConvertModels > 0 ) && ( false == asBinary.empty() ) ) { SaveToBinFile( asBinary ); asBinary = ""; // zablokowanie powtórnego zapisu diff --git a/Model3d.h b/Model3d.h index 8244835d..b7ee145f 100644 --- a/Model3d.h +++ b/Model3d.h @@ -9,15 +9,12 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "GL/glew.h" -#include "Parser.h" +#include "classes.h" #include "dumb3d.h" #include "Float3d.h" #include "openglgeometrybank.h" #include "material.h" -using namespace Math3D; - // Ra: specjalne typy submodeli, poza tym GL_TRIANGLES itp. const int TP_ROTATOR = 256; const int TP_FREESPOTLIGHT = 257; @@ -165,9 +162,9 @@ public: TSubModel * ChildGet() { return Child; }; int TriangleAdd(TModel3d *m, material_handle tex, int tri); void SetRotate(float3 vNewRotateAxis, float fNewAngle); - void SetRotateXYZ(vector3 vNewAngles); + void SetRotateXYZ( Math3D::vector3 vNewAngles); void SetRotateXYZ(float3 vNewAngles); - void SetTranslate(vector3 vNewTransVector); + void SetTranslate( Math3D::vector3 vNewTransVector); void SetTranslate(float3 vNewTransVector); void SetRotateIK1(float3 vNewAngles); TSubModel * GetFromName( std::string const &search, bool i = true ); diff --git a/PyInt.cpp b/PyInt.cpp index 3bfbade0..c59917af 100644 --- a/PyInt.cpp +++ b/PyInt.cpp @@ -1,11 +1,11 @@ #include "stdafx.h" #include "PyInt.h" + +#include "parser.h" #include "renderer.h" +#include "model3d.h" #include "Train.h" #include "Logs.h" -//#include -//#include -//#include TPythonInterpreter *TPythonInterpreter::_instance = NULL; diff --git a/PyInt.h b/PyInt.h index 93720d7c..fa76e7a0 100644 --- a/PyInt.h +++ b/PyInt.h @@ -12,8 +12,7 @@ #else #include "Python.h" #endif -#include "parser.h" -#include "Model3d.h" +#include "classes.h" #define PyGetFloat(param) PyFloat_FromDouble(param >= 0 ? param : -param) #define PyGetFloatS(param) PyFloat_FromDouble(param) diff --git a/ResourceManager.h b/ResourceManager.h index 92fec3ca..81e631a8 100644 --- a/ResourceManager.h +++ b/ResourceManager.h @@ -18,54 +18,6 @@ enum class resource_state { failed }; -/* -#include -#include - -class Resource -{ - - public: - virtual void Release() = 0; - double GetLastUsage() const - { - return _lastUsage; - } - - protected: - void SetLastUsage(double const lastUsage) - { - _lastUsage = lastUsage; - } - - private: - double _lastUsage = 0.0; -}; - -class ResourceManager -{ - - public: - static void Register(Resource *resource); - static void Unregister(Resource *resource); - - static void Sweep(double currentTime); - static void SetExpiry(double expiry) - { - _expiry = expiry; - } - - private: - typedef std::vector Resources; - - static double _expiry; - static double _lastUpdate; - static double _lastReport; - - static Resources _resources; -}; -*/ - using resource_timestamp = std::chrono::steady_clock::time_point; // takes containers providing access to specific element through operator[] diff --git a/Segment.cpp b/Segment.cpp index ed478390..fdd82ece 100644 --- a/Segment.cpp +++ b/Segment.cpp @@ -12,8 +12,9 @@ http://mozilla.org/MPL/2.0/. #include "Globals.h" #include "Logs.h" -#include "Usefull.h" +#include "utilities.h" #include "Track.h" +#include "renderer.h" //--------------------------------------------------------------------------- @@ -61,7 +62,7 @@ bool TSegment::Init( Math3D::vector3 &NewPoint1, Math3D::vector3 NewCPointOut, M // poprawienie przechyłki fRoll1 = glm::radians(fNewRoll1); // Ra: przeliczone jest bardziej przydatne do obliczeń fRoll2 = glm::radians(fNewRoll2); - if (Global::bRollFix) + if (Global.bRollFix) { // Ra: poprawianie przechyłki // Przechyłka powinna być na środku wewnętrznej szyny, a standardowo jest w osi // toru. Dlatego trzeba podnieść tor oraz odpowiednio podwyższyć podsypkę. diff --git a/Segment.h b/Segment.h index 0cc000a8..4b138fe4 100644 --- a/Segment.h +++ b/Segment.h @@ -9,10 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "openglgeometrybank.h" +#include "classes.h" #include "dumb3d.h" -#include "Classes.h" -#include "usefull.h" +#include "openglgeometrybank.h" +#include "utilities.h" class TSegment { // aproksymacja toru (zwrotnica ma dwa takie, jeden z nich jest aktywny) diff --git a/Spring.cpp b/Spring.cpp index 38104815..8a665677 100644 --- a/Spring.cpp +++ b/Spring.cpp @@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/. TSpring::TSpring() { - vForce1 = vForce2 = vector3(0, 0, 0); + vForce1 = vForce2 = Math3D::vector3(0, 0, 0); Ks = 0; Kd = 0; restLen = 0; @@ -29,15 +29,15 @@ void TSpring::Init(double nrestLen, double nKs, double nKd) restLen = nrestLen; } -Math3D::vector3 TSpring::ComputateForces(vector3 const &pPosition1, vector3 const &pPosition2) +Math3D::vector3 TSpring::ComputateForces( Math3D::vector3 const &pPosition1, Math3D::vector3 const &pPosition2) { double dist, Hterm, Dterm; - vector3 springForce, deltaV, deltaP; + Math3D::vector3 springForce, deltaV; // p1 = &system[spring->p1]; // p2 = &system[spring->p2]; // VectorDifference(&p1->pos,&p2->pos,&deltaP); // Vector distance - deltaP = pPosition1 - pPosition2; + auto deltaP = pPosition1 - pPosition2; // dist = VectorLength(&deltaP); // Magnitude of // deltaP dist = deltaP.Length(); diff --git a/Spring.h b/Spring.h index e716b8b9..46c78d72 100644 --- a/Spring.h +++ b/Spring.h @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #ifndef ParticlesH #define ParticlesH +#include "dumb3d.h" + #define STATIC_THRESHOLD 0.17f // efine STATIC_THRESHOLD 0.03f const double m_Kd = 0.02f; // DAMPING FACTOR @@ -20,9 +22,6 @@ const double m_Ksd = 0.1f; // SPRING DAMPING CONSTANT const double m_Csf = 0.9f; // Default Static Friction const double m_Ckf = 0.7f; // Default Kinetic Friction -#include "dumb3d.h" -using namespace Math3D; - class TSpring { public: @@ -31,9 +30,9 @@ class TSpring // void Init(TParticnp1, TParticle *np2, double nKs= 0.5f, double nKd= 0.002f, // double nrestLen= -1.0f); void Init(double nrestLen, double nKs = 0.5f, double nKd = 0.002f); - Math3D::vector3 ComputateForces(vector3 const &pPosition1, vector3 const &pPosition2); + Math3D::vector3 ComputateForces( Math3D::vector3 const &pPosition1, Math3D::vector3 const &pPosition2); void Render(); - vector3 vForce1, vForce2; + Math3D::vector3 vForce1, vForce2; double restLen; // LENGTH OF SPRING AT REST double Ks; // SPRING CONSTANT double Kd; // SPRING DAMPING diff --git a/Texture.cpp b/Texture.cpp index bd4bce23..7cb3654e 100644 --- a/Texture.cpp +++ b/Texture.cpp @@ -19,7 +19,7 @@ http://mozilla.org/MPL/2.0/. #include #include "GL/glew.h" -#include "usefull.h" +#include "utilities.h" #include "globals.h" #include "logs.h" #include "sn_utils.h" @@ -250,7 +250,7 @@ opengl_texture::load_DDS() { int blockSize = ( data_format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ? 8 : 16 ); int offset = 0; - while( ( data_width > Global::iMaxTextureSize ) || ( data_height > Global::iMaxTextureSize ) ) { + while( ( data_width > Global.iMaxTextureSize ) || ( data_height > Global.iMaxTextureSize ) ) { // pomijanie zbyt dużych mipmap, jeśli wymagane jest ograniczenie rozmiaru offset += ( ( data_width + 3 ) / 4 ) * ( ( data_height + 3 ) / 4 ) * blockSize; data_width /= 2; @@ -485,7 +485,7 @@ opengl_texture::load_TGA() { } downsize( GL_BGRA ); - if( ( data_width > Global::iMaxTextureSize ) || ( data_height > Global::iMaxTextureSize ) ) { + if( ( data_width > Global.iMaxTextureSize ) || ( data_height > Global.iMaxTextureSize ) ) { // for non-square textures there's currently possibility the scaling routine will have to abort // before it gets all work done data_state = resource_state::failed; @@ -589,8 +589,8 @@ opengl_texture::create() { } } - if( ( true == Global::ResourceMove ) - || ( false == Global::ResourceSweep ) ) { + if( ( true == Global.ResourceMove ) + || ( false == Global.ResourceSweep ) ) { // if garbage collection is disabled we don't expect having to upload the texture more than once data = std::vector(); data_state = resource_state::none; @@ -607,7 +607,7 @@ opengl_texture::release() { if( id == -1 ) { return; } - if( true == Global::ResourceMove ) { + if( true == Global.ResourceMove ) { // if resource move is enabled we don't keep a cpu side copy after upload // so need to re-acquire the data before release // TBD, TODO: instead of vram-ram transfer fetch the data 'normally' from the disk using worker thread @@ -653,7 +653,7 @@ opengl_texture::set_filtering() const { if( GLEW_EXT_texture_filter_anisotropic ) { // anisotropic filtering - ::glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, Global::AnisotropicFiltering ); + ::glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, Global.AnisotropicFiltering ); } bool sharpen{ false }; @@ -679,7 +679,7 @@ opengl_texture::set_filtering() const { void opengl_texture::downsize( GLuint const Format ) { - while( ( data_width > Global::iMaxTextureSize ) || ( data_height > Global::iMaxTextureSize ) ) { + while( ( data_width > Global.iMaxTextureSize ) || ( data_height > Global.iMaxTextureSize ) ) { // scale down the base texture, if it's larger than allowed maximum // NOTE: scaling is uniform along both axes, meaning non-square textures can drop below the maximum // TODO: replace with proper scaling function once we have image middleware in place @@ -760,7 +760,7 @@ texture_manager::create( std::string Filename, bool const Loadnow ) { std::vector extensions{ { ".dds" }, { ".tga" }, { ".bmp" }, { ".ext" } }; // try to locate requested texture in the databank - auto lookup = find_in_databank( Filename + Global::szDefaultExt ); + auto lookup = find_in_databank( Filename + Global.szDefaultExt ); if( lookup != npos ) { // start with the default extension... return lookup; @@ -769,7 +769,7 @@ texture_manager::create( std::string Filename, bool const Loadnow ) { // ...then try recognized file extensions other than default for( auto const &extension : extensions ) { - if( extension == Global::szDefaultExt ) { + if( extension == Global.szDefaultExt ) { // we already tried this one continue; } @@ -781,12 +781,12 @@ texture_manager::create( std::string Filename, bool const Loadnow ) { } } // if we don't have the texture in the databank, check if it's on disk - std::string filename = find_on_disk( Filename + Global::szDefaultExt ); + std::string filename = find_on_disk( Filename + Global.szDefaultExt ); if( true == filename.empty() ) { // if the default lookup fails, try other known extensions for( auto const &extension : extensions ) { - if( extension == Global::szDefaultExt ) { + if( extension == Global.szDefaultExt ) { // we already tried this one continue; } diff --git a/Timer.cpp b/Timer.cpp index 6220655a..bfbdc456 100644 --- a/Timer.cpp +++ b/Timer.cpp @@ -55,7 +55,7 @@ double GetFPS() void ResetTimers() { - UpdateTimers( Global::iPause != 0 ); + UpdateTimers( Global.iPause != 0 ); DeltaTime = 0.1; DeltaRenderTime = 0.0; fSoundTimer = 0.0; @@ -70,7 +70,7 @@ void UpdateTimers(bool pause) { DeltaRenderTime = double(count - oldCount) / double(fr); if (!pause) { - DeltaTime = Global::fTimeSpeed * DeltaRenderTime; + DeltaTime = Global.fTimeSpeed * DeltaRenderTime; fSoundTimer += DeltaTime; if (fSoundTimer > 0.1) fSoundTimer = 0.0; diff --git a/Track.cpp b/Track.cpp index c40349f0..c7082bb4 100644 --- a/Track.cpp +++ b/Track.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "globals.h" #include "timer.h" #include "logs.h" +#include "renderer.h" // 101206 Ra: trapezoidalne drogi i tory // 110720 Ra: rozprucie zwrotnicy i odcinki izolowane @@ -105,7 +106,7 @@ void TIsolated::Modify(int i, TDynamicObject *o) { // jeśli po zmianie nie ma żadnej osi na odcinku izolowanym if (evFree) simulation::Events.AddToQuery(evFree, o); // dodanie zwolnienia do kolejki - if (Global::iMultiplayer) // jeśli multiplayer + if (Global.iMultiplayer) // jeśli multiplayer multiplayer::WyslijString(asName, 10); // wysłanie pakietu o zwolnieniu if (pMemCell) // w powiązanej komórce pMemCell->UpdateValues( "", 0, int( pMemCell->Value2() ) & ~0xFF, @@ -119,7 +120,7 @@ void TIsolated::Modify(int i, TDynamicObject *o) { if (evBusy) simulation::Events.AddToQuery(evBusy, o); // dodanie zajętości do kolejki - if (Global::iMultiplayer) // jeśli multiplayer + if (Global.iMultiplayer) // jeśli multiplayer multiplayer::WyslijString(asName, 11); // wysłanie pakietu o zajęciu if (pMemCell) // w powiązanej komórce pMemCell->UpdateValues( "", 0, int( pMemCell->Value2() ) | 1, update_memval2 ); // zmieniamy ostatnią wartość na nieparzystą @@ -175,7 +176,7 @@ TTrack * TTrack::Create400m(int what, double dx) trk->m_visible = false; // nie potrzeba pokazywać, zresztą i tak nie ma tekstur trk->iCategoryFlag = what; // taki sam typ plus informacja, że dodatkowy trk->Init(); // utworzenie segmentu - trk->Segment->Init( vector3( -dx, 0, 0 ), vector3( -dx, 0, 400 ), 10.0, 0, 0 ); // prosty + trk->Segment->Init( Math3D::vector3( -dx, 0, 0 ), Math3D::vector3( -dx, 0, 400 ), 10.0, 0, 0 ); // prosty trk->location( glm::dvec3{ -dx, 0, 200 } ); //środek, aby się mogło wyświetlić simulation::Paths.insert( trk ); simulation::Region->insert_path( trk, scene::scratch_data() ); @@ -194,7 +195,7 @@ TTrack * TTrack::NullCreate(int dir) trk->iCategoryFlag = (iCategoryFlag & 15) | 0x80; // taki sam typ plus informacja, że dodatkowy float r1, r2; Segment->GetRolls(r1, r2); // pobranie przechyłek na początku toru - vector3 p1, cv1, cv2, p2; // będziem tworzyć trajektorię lotu + Math3D::vector3 p1, cv1, cv2, p2; // będziem tworzyć trajektorię lotu if (iCategoryFlag & 1) { // tylko dla kolei trk->iDamageFlag = 128; // wykolejenie @@ -248,10 +249,10 @@ TTrack * TTrack::NullCreate(int dir) cv1 = -20.0 * Normalize(Segment->GetDirection1()); // pierwszy wektor kontrolny p2 = p1 + cv1 + cv1; // 40m // bo prosty, kontrolne wyliczane przy zmiennej przechyłce - trk->Segment->Init(p1, p1 + cv1, p2 + vector3(-cv1.z, cv1.y, cv1.x), p2, 2, -RadToDeg(r1), 0.0); + trk->Segment->Init(p1, p1 + cv1, p2 + Math3D::vector3(-cv1.z, cv1.y, cv1.x), p2, 2, -RadToDeg(r1), 0.0); ConnectPrevPrev(trk, 0); // bo prosty, kontrolne wyliczane przy zmiennej przechyłce - trk2->Segment->Init(p1, p1 + cv1, p2 + vector3(cv1.z, cv1.y, -cv1.x), p2, 2, -RadToDeg(r1), 0.0); + trk2->Segment->Init(p1, p1 + cv1, p2 + Math3D::vector3(cv1.z, cv1.y, -cv1.x), p2, 2, -RadToDeg(r1), 0.0); trk2->iPrevDirection = 0; // zwrotnie do tego samego odcinka break; case 1: @@ -259,10 +260,10 @@ TTrack * TTrack::NullCreate(int dir) cv1 = -20.0 * Normalize(Segment->GetDirection2()); // pierwszy wektor kontrolny p2 = p1 + cv1 + cv1; // bo prosty, kontrolne wyliczane przy zmiennej przechyłce - trk->Segment->Init(p1, p1 + cv1, p2 + vector3(-cv1.z, cv1.y, cv1.x), p2, 2, RadToDeg(r2), 0.0); + trk->Segment->Init(p1, p1 + cv1, p2 + Math3D::vector3(-cv1.z, cv1.y, cv1.x), p2, 2, RadToDeg(r2), 0.0); ConnectNextPrev(trk, 0); // bo prosty, kontrolne wyliczane przy zmiennej przechyłce - trk2->Segment->Init(p1, p1 + cv1, p2 + vector3(cv1.z, cv1.y, -cv1.x), p2, 2, RadToDeg(r2), 0.0); + trk2->Segment->Init(p1, p1 + cv1, p2 + Math3D::vector3(cv1.z, cv1.y, -cv1.x), p2, 2, RadToDeg(r2), 0.0); trk2->iPrevDirection = 1; // zwrotnie do tego samego odcinka break; } @@ -342,17 +343,17 @@ void TTrack::ConnectNextNext(TTrack *pTrack, int typ) } } -vector3 LoadPoint(cParser *parser) +Math3D::vector3 LoadPoint(cParser *parser) { // pobranie współrzędnych punktu - vector3 p; + Math3D::vector3 p; parser->getTokens(3); *parser >> p.x >> p.y >> p.z; return p; } -void TTrack::Load(cParser *parser, vector3 pOrigin) +void TTrack::Load(cParser *parser, Math3D::vector3 pOrigin) { // pobranie obiektu trajektorii ruchu - vector3 pt, vec, p1, p2, cp1, cp2, p3, p4, cp3, cp4; // dodatkowe punkty potrzebne do skrzyżowań + Math3D::vector3 pt, vec, p1, p2, cp1, cp2, p3, p4, cp3, cp4; // dodatkowe punkty potrzebne do skrzyżowań double a1, a2, r1, r2, r3, r4; std::string str; size_t i; //,state; //Ra: teraz już nie ma początkowego stanu zwrotnicy we wpisie @@ -403,7 +404,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) } else eType = tt_Unknown; - if (Global::iWriteLogEnabled & 4) + if (Global.iWriteLogEnabled & 4) WriteLog(str); parser->getTokens(4); float discard {}; @@ -466,7 +467,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) if (iCategoryFlag & 4) fTexHeight1 = -fTexHeight1; // rzeki mają wysokość odwrotnie niż drogi } - else if (Global::iWriteLogEnabled & 4) + else if (Global.iWriteLogEnabled & 4) WriteLog("unvis"); Init(); // ustawia SwitchExtension double segsize = 5.0; // długość odcinka segmentowania @@ -499,7 +500,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) if( fRadius != 0 ) { // gdy podany promień - segsize = clamp( std::abs( fRadius ) * ( 0.02 / Global::SplineFidelity ), 2.0 / Global::SplineFidelity, 10.0 ); + segsize = clamp( std::abs( fRadius ) * ( 0.02 / Global.SplineFidelity ), 2.0 / Global.SplineFidelity, 10.0 ); } else { // HACK: crude check whether claimed straight is an actual straight piece @@ -509,12 +510,12 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) } else { // HACK: divide roughly in 10 segments. - segsize = clamp( ( p1 - p2 ).Length() * ( 0.1 / Global::SplineFidelity ), 2.0 / Global::SplineFidelity, 10.0 ); + segsize = clamp( ( p1 - p2 ).Length() * ( 0.1 / Global.SplineFidelity ), 2.0 / Global.SplineFidelity, 10.0 ); } } - if( ( cp1 == vector3( 0, 0, 0 ) ) - && ( cp2 == vector3( 0, 0, 0 ) ) ) { + if( ( cp1 == Math3D::vector3( 0, 0, 0 ) ) + && ( cp2 == Math3D::vector3( 0, 0, 0 ) ) ) { // Ra: hm, czasem dla prostego są podane... // gdy prosty, kontrolne wyliczane przy zmiennej przechyłce Segment->Init( p1, p2, segsize, r1, r2 ); @@ -582,7 +583,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) segsize = 5.0; } // ułomny prosty - if (!(cp1 == vector3(0, 0, 0)) && !(cp2 == vector3(0, 0, 0))) + if (!(cp1 == Math3D::vector3(0, 0, 0)) && !(cp2 == Math3D::vector3(0, 0, 0))) SwitchExtension->Segments[0]->Init(p1, p1 + cp1, p2 + cp2, p2, segsize, r1, r2); else SwitchExtension->Segments[0]->Init(p1, p2, segsize, r1, r2); @@ -613,7 +614,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) segsize = 5.0; } // ułomny prosty - if (!(cp3 == vector3(0, 0, 0)) && !(cp4 == vector3(0, 0, 0))) + if (!(cp3 == Math3D::vector3(0, 0, 0)) && !(cp4 == Math3D::vector3(0, 0, 0))) { // dla skrzyżowania dróg dać odwrotnie końce, żeby brzegi generować lewym if (eType != tt_Cross) SwitchExtension->Segments[1]->Init(p3, p3 + cp3, p4 + cp4, p4, segsize, r3, r4); @@ -641,7 +642,7 @@ void TTrack::Load(cParser *parser, vector3 pOrigin) if( eType == tt_Switch ) // Ra: zamienić później na iloczyn wektorowy { - vector3 v1, v2; + Math3D::vector3 v1, v2; double a1, a2; v1 = SwitchExtension->Segments[0]->FastGetPoint_1() - SwitchExtension->Segments[0]->FastGetPoint_0(); @@ -940,7 +941,7 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) Dynamic->MyTrack = NULL; // trzeba by to uzależnić od kierunku ruchu... return true; } - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { // pierwszy zajmujący @@ -1032,7 +1033,7 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { // jeśli już nie ma żadnego @@ -1707,14 +1708,14 @@ void TTrack::create_geometry( gfx::geometrybank_handle const &Bank ) { case tt_Cross: // skrzyżowanie dróg rysujemy inaczej { // ustalenie współrzędnych środka - przecięcie Point1-Point2 z CV4-Point4 double a[4]; // kąty osi ulic wchodzących - vector3 p[4]; // punkty się przydadzą do obliczeń + Math3D::vector3 p[4]; // punkty się przydadzą do obliczeń // na razie połowa odległości pomiędzy Point1 i Point2, potem się dopracuje a[0] = a[1] = 0.5; // parametr do poszukiwania przecięcia łuków // modyfikować a[0] i a[1] tak, aby trafić na przecięcie odcinka 34 p[0] = SwitchExtension->Segments[0]->FastGetPoint(a[0]); // współrzędne środka pierwszego odcinka p[1] = SwitchExtension->Segments[1]->FastGetPoint(a[1]); //-//- drugiego // p[2]=p[1]-p[0]; //jeśli różne od zera, przeliczyć a[0] i a[1] i wyznaczyć nowe punkty - vector3 oxz = p[0]; // punkt mapowania środka tekstury skrzyżowania + Math3D::vector3 oxz = p[0]; // punkt mapowania środka tekstury skrzyżowania p[0] = SwitchExtension->Segments[0]->GetDirection1(); // Point1 - pobranie wektorów kontrolnych p[1] = SwitchExtension->Segments[1]->GetDirection2(); // Point3 (bo zamienione) p[2] = SwitchExtension->Segments[0]->GetDirection2(); // Point2 @@ -2166,37 +2167,6 @@ void TTrack::create_geometry( gfx::geometrybank_handle const &Bank ) { return; }; -void TTrack::EnvironmentSet() -{ // ustawienie zmienionego światła - switch( eEnvironment ) { - case e_canyon: { - Global::DayLight.apply_intensity( 0.4f ); - break; - } - case e_tunnel: { - Global::DayLight.apply_intensity( 0.2f ); - break; - } - default: { - break; - } - } -}; - -void TTrack::EnvironmentReset() -{ // przywrócenie domyślnego światła - switch( eEnvironment ) { - case e_canyon: - case e_tunnel: { - Global::DayLight.apply_intensity(); - break; - } - default: { - break; - } - } -}; - void TTrack::RenderDynSounds() { // odtwarzanie dźwięków pojazdów jest niezależne od ich wyświetlania for( auto dynamic : Dynamics ) { @@ -2535,11 +2505,11 @@ TTrack * TTrack::RaAnimate() double sina = -hlen * std::sin(glm::radians(SwitchExtension->fOffset)), cosa = -hlen * std::cos(glm::radians(SwitchExtension->fOffset)); SwitchExtension->vTrans = ac->TransGet(); - vector3 middle = + auto middle = location() + SwitchExtension->vTrans; // SwitchExtension->Segments[0]->FastGetPoint(0.5); - Segment->Init(middle + vector3(sina, 0.0, cosa), - middle - vector3(sina, 0.0, cosa), 10.0); // nowy odcinek + Segment->Init(middle + Math3D::vector3(sina, 0.0, cosa), + middle - Math3D::vector3(sina, 0.0, cosa), 10.0); // nowy odcinek for( auto dynamic : Dynamics ) { // minimalny ruch, aby przeliczyć pozycję dynamic->Move( 0.000001 ); @@ -2579,7 +2549,7 @@ bool TTrack::IsGroupable() return true; }; -bool Equal(vector3 v1, vector3 *v2) +bool Equal( Math3D::vector3 v1, Math3D::vector3 *v2) { // sprawdzenie odległości punktów // Ra: powinno być do 100cm wzdłuż toru i ze 2cm w poprzek (na prostej może nie być długiego // kawałka) @@ -2594,7 +2564,7 @@ bool Equal(vector3 v1, vector3 *v2) // return (SquareMagnitude(v1-*v2)<0.00012); //0.011^2=0.00012 }; -int TTrack::TestPoint(vector3 *Point) +int TTrack::TestPoint( Math3D::vector3 *Point) { // sprawdzanie, czy tory można połączyć switch (eType) { @@ -2822,7 +2792,7 @@ path_table::InitTracks() { auto const trackname { track->name() }; - if( ( Global::iHiddenEvents & 1 ) + if( ( Global.iHiddenEvents & 1 ) && ( false == trackname.empty() ) ) { // jeśli podana jest nazwa torów, można szukać eventów skojarzonych przez nazwę track->AssignEvents( diff --git a/Track.h b/Track.h index ee569462..f7494dc3 100644 --- a/Track.h +++ b/Track.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "classes.h" #include "Segment.h" #include "material.h" #include "scenenode.h" @@ -273,10 +274,6 @@ protected: // calculates path's bounding radius void radius_(); - -private: - void EnvironmentSet(); - void EnvironmentReset(); }; diff --git a/Traction.cpp b/Traction.cpp index 6ff114b3..cf7705a7 100644 --- a/Traction.cpp +++ b/Traction.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation.h" #include "Globals.h" #include "logs.h" +#include "renderer.h" //--------------------------------------------------------------------------- /* @@ -576,9 +577,9 @@ TTraction::wire_color() const { default: {break; } } // w zaleźności od koloru swiatła - color.r *= Global::DayLight.ambient[ 0 ]; - color.g *= Global::DayLight.ambient[ 1 ]; - color.b *= Global::DayLight.ambient[ 2 ]; + color.r *= Global.DayLight.ambient[ 0 ]; + color.g *= Global.DayLight.ambient[ 1 ]; + color.b *= Global.DayLight.ambient[ 2 ]; } else { // tymczasowo pokazanie zasilanych odcinków diff --git a/TractionPower.cpp b/TractionPower.cpp index c83eb49a..8b0d309e 100644 --- a/TractionPower.cpp +++ b/TractionPower.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "TractionPower.h" +#include "parser.h" #include "Logs.h" //--------------------------------------------------------------------------- diff --git a/TractionPower.h b/TractionPower.h index f170e738..1a30c320 100644 --- a/TractionPower.h +++ b/TractionPower.h @@ -9,8 +9,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include "classes.h" #include "scenenode.h" -#include "parser.h" //Tolaris-010603 #include "names.h" class TTractionPowerSource : public editor::basic_node { diff --git a/Train.cpp b/Train.cpp index 0b81c1ea..06d44e95 100644 --- a/Train.cpp +++ b/Train.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "Globals.h" #include "simulation.h" +#include "world.h" +#include "camera.h" #include "Logs.h" #include "MdlMngr.h" #include "Timer.h" @@ -317,9 +319,9 @@ TTrain::TTrain() { fPPress = fNPress = 0; // asMessage=""; - pMechShake = vector3(0, 0, 0); - vMechMovement = vector3(0, 0, 0); - pMechOffset = vector3(0, 0, 0); + pMechShake = Math3D::vector3(0, 0, 0); + vMechMovement = Math3D::vector3(0, 0, 0); + pMechOffset = Math3D::vector3(0, 0, 0); fBlinkTimer = 0; fHaslerTimer = 0; DynamicSet(NULL); // ustawia wszystkie mv* @@ -328,7 +330,7 @@ TTrain::TTrain() { bCabLight = false; bCabLightDim = false; //----- - pMechSittingPosition = vector3(0, 0, 0); // ABu: 180404 + pMechSittingPosition = Math3D::vector3(0, 0, 0); // ABu: 180404 InstrumentLightActive = false; // ABu: 030405 fTachoTimer = 0.0; // włączenie skoków wskazań prędkościomierza @@ -356,7 +358,7 @@ TTrain::TTrain() { bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) { // powiązanie ręcznego sterowania kabiną z pojazdem - // Global::pUserDynamic=NewDynamicObject; //pojazd renderowany bez trzęsienia + // Global.pUserDynamic=NewDynamicObject; //pojazd renderowany bez trzęsienia DynamicSet(NewDynamicObject); if (!e3d) if (DynamicObject->Mechanik == NULL) @@ -376,8 +378,8 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) } */ MechSpring.Init(0.015, 250); - vMechVelocity = vector3(0, 0, 0); - pMechOffset = vector3( 0, 0, 0 ); + vMechVelocity = Math3D::vector3(0, 0, 0); + pMechOffset = Math3D::vector3( 0, 0, 0 ); fMechSpringX = 1; fMechSpringY = 0.5; fMechSpringZ = 0.5; @@ -814,7 +816,7 @@ void TTrain::OnCommand_trainbrakeincrease( TTrain *Train, command_data const &Co Train->mvOccupied->BrakeLevelAdd( 0.1 /*15.0 * Command.time_delta*/ ); } else { - Train->set_train_brake( Train->mvOccupied->BrakeCtrlPos + Global::fBrakeStep ); + Train->set_train_brake( Train->mvOccupied->BrakeCtrlPos + Global.fBrakeStep ); } } } @@ -827,7 +829,7 @@ void TTrain::OnCommand_trainbrakedecrease( TTrain *Train, command_data const &Co Train->mvOccupied->BrakeLevelAdd( -0.1 /*-15.0 * Command.time_delta*/ ); } else { - Train->set_train_brake( Train->mvOccupied->BrakeCtrlPos - Global::fBrakeStep ); + Train->set_train_brake( Train->mvOccupied->BrakeCtrlPos - Global.fBrakeStep ); } } else { @@ -835,7 +837,7 @@ void TTrain::OnCommand_trainbrakedecrease( TTrain *Train, command_data const &Co if( ( Train->mvOccupied->BrakeCtrlPos == -1 ) && ( Train->mvOccupied->BrakeHandle == FVel6 ) && ( Train->DynamicObject->Controller != AIdriver ) - && ( Global::iFeedbackMode < 3 ) ) { + && ( Global.iFeedbackMode < 3 ) ) { // Odskakiwanie hamulce EP Train->set_train_brake( 0 ); } @@ -853,7 +855,7 @@ void TTrain::OnCommand_trainbrakecharging( TTrain *Train, command_data const &Co if( ( Train->mvOccupied->BrakeCtrlPos == -1 ) && ( Train->mvOccupied->BrakeHandle == FVel6 ) && ( Train->DynamicObject->Controller != AIdriver ) - && ( Global::iFeedbackMode < 3 ) ) { + && ( Global.iFeedbackMode < 3 ) ) { // Odskakiwanie hamulce EP Train->set_train_brake( 0 ); } @@ -2576,14 +2578,14 @@ void TTrain::OnCommand_redmarkerstoggle( TTrain *Train, command_data const &Comm if( ( true == FreeFlyModeFlag ) && ( Command.action == GLFW_PRESS ) ) { - auto *vehicle { std::get( simulation::Region->find_vehicle( Global::pCameraPosition, 10, false, true ) ) }; + auto *vehicle { std::get( simulation::Region->find_vehicle( Global.pCameraPosition, 10, false, true ) ) }; if( vehicle == nullptr ) { return; } int const CouplNr { clamp( vehicle->DirectionGet() - * ( LengthSquared3( vehicle->HeadPosition() - Global::pCameraPosition ) > LengthSquared3( vehicle->RearPosition() - Global::pCameraPosition ) ? + * ( LengthSquared3( vehicle->HeadPosition() - Global.pCameraPosition ) > LengthSquared3( vehicle->RearPosition() - Global.pCameraPosition ) ? 1 : -1 ), 0, 1 ) }; // z [-1,1] zrobić [0,1] @@ -2602,14 +2604,14 @@ void TTrain::OnCommand_endsignalstoggle( TTrain *Train, command_data const &Comm if( ( true == FreeFlyModeFlag ) && ( Command.action == GLFW_PRESS ) ) { - auto *vehicle { std::get( simulation::Region->find_vehicle( Global::pCameraPosition, 10, false, true ) ) }; + auto *vehicle { std::get( simulation::Region->find_vehicle( Global.pCameraPosition, 10, false, true ) ) }; if( vehicle == nullptr ) { return; } int const CouplNr { clamp( vehicle->DirectionGet() - * ( LengthSquared3( vehicle->HeadPosition() - Global::pCameraPosition ) > LengthSquared3( vehicle->RearPosition() - Global::pCameraPosition ) ? + * ( LengthSquared3( vehicle->HeadPosition() - Global.pCameraPosition ) > LengthSquared3( vehicle->RearPosition() - Global.pCameraPosition ) ? 1 : -1 ), 0, 1 ) }; // z [-1,1] zrobić [0,1] @@ -3141,8 +3143,8 @@ void TTrain::OnCommand_cabchangeforward( TTrain *Train, command_data const &Comm if( false == Train->CabChange( 1 ) ) { if( TestFlag( Train->DynamicObject->MoverParameters->Couplers[ side::front ].CouplingFlag, coupling::gangway ) ) { // przejscie do nastepnego pojazdu - Global::changeDynObj = Train->DynamicObject->PrevConnected; - Global::changeDynObj->MoverParameters->ActiveCab = ( + Global.changeDynObj = Train->DynamicObject->PrevConnected; + Global.changeDynObj->MoverParameters->ActiveCab = ( Train->DynamicObject->PrevConnectedNo ? -1 : 1 ); @@ -3157,8 +3159,8 @@ void TTrain::OnCommand_cabchangebackward( TTrain *Train, command_data const &Com if( false == Train->CabChange( -1 ) ) { if( TestFlag( Train->DynamicObject->MoverParameters->Couplers[ side::rear ].CouplingFlag, coupling::gangway ) ) { // przejscie do nastepnego pojazdu - Global::changeDynObj = Train->DynamicObject->NextConnected; - Global::changeDynObj->MoverParameters->ActiveCab = ( + Global.changeDynObj = Train->DynamicObject->NextConnected; + Global.changeDynObj->MoverParameters->ActiveCab = ( Train->DynamicObject->NextConnectedNo ? -1 : 1 ); @@ -3189,13 +3191,13 @@ void TTrain::UpdateMechPosition(double dt) // Granice mozna ustalic doswiadczalnie. Ja proponuje 14:20 double const iVel = std::min( DynamicObject->GetVelocity(), 150.0 ); - if( !Global::iSlowMotion // musi być pełna prędkość + if( !Global.iSlowMotion // musi być pełna prędkość && ( pMechOffset.y < 4.0 ) ) // Ra 15-01: przy oglądaniu pantografu bujanie przeszkadza { if( iVel > 0.5 ) { // acceleration-driven base shake shake += 1.25 * MechSpring.ComputateForces( - vector3( + Math3D::vector3( -mvControlled->AccN * dt * 5.0, // highlight side sway -mvControlled->AccVert * dt, -mvControlled->AccSVBased * dt * 1.25 ), // accent acceleration/deceleration @@ -3204,7 +3206,7 @@ void TTrain::UpdateMechPosition(double dt) if( Random( iVel ) > 25.0 ) { // extra shake at increased velocity shake += MechSpring.ComputateForces( - vector3( + Math3D::vector3( ( Random( iVel * 2 ) - iVel ) / ( ( iVel * 2 ) * 4 ) * fMechSpringX, ( Random( iVel * 2 ) - iVel ) / ( ( iVel * 2 ) * 4 ) * fMechSpringY, ( Random( iVel * 2 ) - iVel ) / ( ( iVel * 2 ) * 4 ) * fMechSpringZ ) @@ -3224,14 +3226,14 @@ void TTrain::UpdateMechPosition(double dt) if( ( pMechShake.y > fMechMaxSpring ) || ( pMechShake.y < -fMechMaxSpring ) ) vMechVelocity.y = -vMechVelocity.y; // ABu011104: 5*pMechShake.y, zeby ladnie pudlem rzucalo :) - pMechPosition = pMechOffset + vector3( 1.5 * pMechShake.x, 2.0 * pMechShake.y, 1.5 * pMechShake.z ); + pMechPosition = pMechOffset + Math3D::vector3( 1.5 * pMechShake.x, 2.0 * pMechShake.y, 1.5 * pMechShake.z ); // vMechMovement = 0.5 * vMechMovement; } else { // hamowanie rzucania przy spadku FPS pMechShake -= pMechShake * std::min( dt, 1.0 ); // po tym chyba potrafią zostać jakieś ułamki, które powodują zjazd pMechOffset += vMechMovement * dt; vMechVelocity.y = 0.5 * vMechVelocity.y; - pMechPosition = pMechOffset + vector3( pMechShake.x, 5 * pMechShake.y, pMechShake.z ); + pMechPosition = pMechOffset + Math3D::vector3( pMechShake.x, 5 * pMechShake.y, pMechShake.z ); // vMechMovement = 0.5 * vMechMovement; } // numer kabiny (-1: kabina B) @@ -3278,10 +3280,10 @@ void TTrain::UpdateMechPosition(double dt) }; // returns position of the mechanic in the scene coordinates -vector3 +Math3D::vector3 TTrain::GetWorldMechPosition() { - vector3 position = DynamicObject->mMatrix * pMechPosition; // położenie względem środka pojazdu w układzie scenerii + auto position = DynamicObject->mMatrix * pMechPosition; // położenie względem środka pojazdu w układzie scenerii position += DynamicObject->GetPosition(); return position; } @@ -3310,13 +3312,13 @@ bool TTrain::Update( double const Deltatime ) // update driver's position { - vector3 Vec = Global::pCamera->Velocity * -2.0;// -7.5 * Timer::GetDeltaRenderTime(); + auto Vec = Global.pCamera->Velocity * -2.0;// -7.5 * Timer::GetDeltaRenderTime(); Vec.y = -Vec.y; if( mvOccupied->ActiveCab < 0 ) { Vec *= -1.0f; Vec.y = -Vec.y; } - Vec.RotateY( Global::pCamera->Yaw ); + Vec.RotateY( Global.pCamera->Yaw ); vMechMovement = Vec; } @@ -3491,7 +3493,7 @@ bool TTrain::Update( double const Deltatime ) fEIMParams[1 + i][9] = 0; } - if (Global::iFeedbackMode == 4) + if (Global.iFeedbackMode == 4) { // wykonywać tylko gdy wyprowadzone na pulpit Console::ValueSet(0, mvOccupied->Compressor); // Ra: sterowanie miernikiem: zbiornik główny @@ -3509,7 +3511,7 @@ bool TTrain::Update( double const Deltatime ) /// napędu } - if (Global::bMWDmasterEnable) // pobieranie danych dla pulpitu port (COM) + if (Global.bMWDmasterEnable) // pobieranie danych dla pulpitu port (COM) { Console::ValueSet(0, mvOccupied->Compressor); // zbiornik główny Console::ValueSet(1, mvOccupied->PipePress); // przewód główny @@ -4067,7 +4069,7 @@ bool TTrain::Update( double const Deltatime ) { if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag ? false : - (Global::iFeedbackMode == 4 || (Global::bMWDmasterEnable && Global::bMWDBreakEnable))) : + (Global.iFeedbackMode == 4 || (Global.bMWDmasterEnable && Global.bMWDBreakEnable))) : false) // nie blokujemy AI { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console @@ -4076,7 +4078,7 @@ bool TTrain::Update( double const Deltatime ) double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; b = clamp( b, -2.0, mvOccupied->BrakeCtrlPosNo ); // przycięcie zmiennej do granic - if (Global::bMWDdebugEnable && Global::iMWDDebugMode & 4) WriteLog("FV4a break position = " + to_string(b)); + if (Global.bMWDdebugEnable && Global.iMWDDebugMode & 4) WriteLog("FV4a break position = " + to_string(b)); ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -4085,7 +4087,7 @@ bool TTrain::Update( double const Deltatime ) double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; b = clamp( b, -1.0, mvOccupied->BrakeCtrlPosNo ); // przycięcie zmiennej do granic - if (Global::bMWDdebugEnable && Global::iMWDDebugMode & 4) WriteLog("FVel6 break position = " + to_string(b)); + if (Global.bMWDdebugEnable && Global.iMWDDebugMode & 4) WriteLog("FVel6 break position = " + to_string(b)); ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -4103,8 +4105,8 @@ bool TTrain::Update( double const Deltatime ) if( ( DynamicObject->Mechanik != nullptr ) && ( false == DynamicObject->Mechanik->AIControllFlag ) // nie blokujemy AI && ( mvOccupied->BrakeLocHandle == FD1 ) - && ( ( Global::iFeedbackMode == 4 ) - || ( Global::bMWDmasterEnable && Global::bMWDBreakEnable ) ) ) { + && ( ( Global.iFeedbackMode == 4 ) + || ( Global.bMWDmasterEnable && Global.bMWDBreakEnable ) ) ) { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console auto const b = clamp( @@ -4113,8 +4115,8 @@ bool TTrain::Update( double const Deltatime ) ManualBrakePosNo ); ggLocalBrake.UpdateValue( b ); // przesów bez zaokrąglenia mvOccupied->LocalBrakePos = int( 1.09 * b ); // sposób zaokrąglania jest do ustalenia - if( ( true == Global::bMWDdebugEnable ) - && ( ( Global::iMWDDebugMode & 4 ) != 0 ) ) { + if( ( true == Global.bMWDdebugEnable ) + && ( ( Global.iMWDDebugMode & 4 ) != 0 ) ) { WriteLog( "FD1 break position = " + to_string( b ) ); } } @@ -4513,7 +4515,7 @@ TTrain::update_sounds( double const Deltatime ) { // szum w czasie jazdy if( ( false == FreeFlyModeFlag ) - && ( false == Global::CabWindowOpen ) + && ( false == Global.CabWindowOpen ) && ( DynamicObject->GetVelocity() > 0.5 ) ) { // frequency calculation @@ -4936,11 +4938,11 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) if (token != "none") { // bieżąca sciezka do tekstur to dynamic/... - Global::asCurrentTexturePath = DynamicObject->asBaseDir; + Global.asCurrentTexturePath = DynamicObject->asBaseDir; // szukaj kabinę jako oddzielny model TModel3d *kabina = TModelsManager::GetModel(DynamicObject->asBaseDir + token, true); // z powrotem defaultowa sciezka do tekstur - Global::asCurrentTexturePath = szTexturePath; + Global.asCurrentTexturePath = szTexturePath; // if (DynamicObject->mdKabina!=k) if (kabina != nullptr) { @@ -5048,23 +5050,23 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) void TTrain::MechStop() { // likwidacja ruchu kamery w kabinie (po powrocie przez [F4]) - pMechPosition = vector3(0, 0, 0); - pMechShake = vector3(0, 0, 0); - vMechMovement = vector3(0, 0, 0); - vMechVelocity = vector3(0, 0, 0); // tu zostawały jakieś ułamki, powodujące uciekanie kamery + pMechPosition = Math3D::vector3(0, 0, 0); + pMechShake = Math3D::vector3(0, 0, 0); + vMechMovement = Math3D::vector3(0, 0, 0); + vMechVelocity = Math3D::vector3(0, 0, 0); // tu zostawały jakieś ułamki, powodujące uciekanie kamery }; -vector3 TTrain::MirrorPosition(bool lewe) +Math3D::vector3 TTrain::MirrorPosition(bool lewe) { // zwraca współrzędne widoku kamery z lusterka switch (iCabn) { case 1: // przednia (1) return DynamicObject->mMatrix * - vector3(lewe ? Cabine[iCabn].CabPos2.x : Cabine[iCabn].CabPos1.x, + Math3D::vector3(lewe ? Cabine[iCabn].CabPos2.x : Cabine[iCabn].CabPos1.x, 1.5 + Cabine[iCabn].CabPos1.y, Cabine[iCabn].CabPos2.z); case 2: // tylna (-1) return DynamicObject->mMatrix * - vector3(lewe ? Cabine[iCabn].CabPos1.x : Cabine[iCabn].CabPos2.x, + Math3D::vector3(lewe ? Cabine[iCabn].CabPos1.x : Cabine[iCabn].CabPos2.x, 1.5 + Cabine[iCabn].CabPos1.y, Cabine[iCabn].CabPos1.z); } return DynamicObject->GetPosition(); // współrzędne środka pojazdu diff --git a/Train.h b/Train.h index 99d4bbe7..bb4e79ab 100644 --- a/Train.h +++ b/Train.h @@ -37,8 +37,8 @@ class TCab void Init(double Initx1, double Inity1, double Initz1, double Initx2, double Inity2, double Initz2, bool InitEnabled, bool InitOccupied); */ void Load(cParser &Parser); - vector3 CabPos1; - vector3 CabPos2; + Math3D::vector3 CabPos1; + Math3D::vector3 CabPos2; bool bEnabled; bool bOccupied; double dimm_r, dimm_g, dimm_b; // McZapkie-120503: tlumienie swiatla @@ -83,11 +83,11 @@ class TTrain // McZapkie-010302 bool Init(TDynamicObject *NewDynamicObject, bool e3d = false); - inline vector3 GetDirection() { return DynamicObject->VectorFront(); }; - inline vector3 GetUp() { return DynamicObject->VectorUp(); }; + inline Math3D::vector3 GetDirection() { return DynamicObject->VectorFront(); }; + inline Math3D::vector3 GetUp() { return DynamicObject->VectorUp(); }; inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); } void UpdateMechPosition(double dt); - vector3 GetWorldMechPosition(); + Math3D::vector3 GetWorldMechPosition(); bool Update( double const Deltatime ); void MechStop(); void SetLights(); @@ -421,11 +421,11 @@ public: // reszta może by?publiczna /* vector3 pPosition; */ - vector3 pMechOffset; // driverNpos - vector3 vMechMovement; - vector3 pMechPosition; - vector3 pMechShake; - vector3 vMechVelocity; + Math3D::vector3 pMechOffset; // driverNpos + Math3D::vector3 vMechMovement; + Math3D::vector3 pMechPosition; + Math3D::vector3 pMechShake; + Math3D::vector3 vMechVelocity; // McZapkie: do poruszania sie po kabinie // McZapkie: opis kabiny - obszar poruszania sie mechanika oraz zajetosc TCab Cabine[maxcab + 1]; // przedzial maszynowy, kabina 1 (A), kabina 2 (B) @@ -468,8 +468,8 @@ public: // reszta może by?publiczna bool bCabLight; // hunter-091012: czy swiatlo jest zapalone? bool bCabLightDim; // hunter-091012: czy przyciemnienie kabiny jest zapalone? - vector3 pMechSittingPosition; // ABu 180404 - vector3 MirrorPosition(bool lewe); + Math3D::vector3 pMechSittingPosition; // ABu 180404 + Math3D::vector3 MirrorPosition(bool lewe); private: double fBlinkTimer; diff --git a/TrkFoll.h b/TrkFoll.h index 2545ba58..4e1a4cfd 100644 --- a/TrkFoll.h +++ b/TrkFoll.h @@ -10,8 +10,8 @@ http://mozilla.org/MPL/2.0/. #ifndef TrkFollH #define TrkFollH -#include "Track.h" -#include "McZapkie\MOVER.h" +#include "classes.h" +#include "segment.h" class TTrackFollower { // oś poruszająca się po torze diff --git a/World.cpp b/World.cpp index 77404f11..a379184e 100644 --- a/World.cpp +++ b/World.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "color.h" #include "uilayer.h" +#include "uitranscripts.h" #include "translation.h" //--------------------------------------------------------------------------- @@ -65,9 +66,9 @@ simulation_time::init() { ::GetLocalTime( &m_time ); - if( Global::fMoveLight > 0.0 ) { + if( Global.fMoveLight > 0.0 ) { // day and month of the year can be overriden by scenario setup - daymonth( m_time.wDay, m_time.wMonth, m_time.wYear, static_cast( Global::fMoveLight ) ); + daymonth( m_time.wDay, m_time.wMonth, m_time.wYear, static_cast( Global.fMoveLight ) ); } if( requestedhour != (WORD)-1 ) { m_time.wHour = clamp( requestedhour, static_cast( 0 ), static_cast( 23 ) ); } @@ -185,7 +186,7 @@ TWorld::TWorld() Train = NULL; for (int i = 0; i < 10; ++i) KeyEvents[i] = NULL; // eventy wyzwalane klawiszami cyfrowymi - Global::iSlowMotion = 0; + Global.iSlowMotion = 0; pDynamicNearest = NULL; fTimeBuffer = 0.0; // bufor czasu aktualizacji dla stałego kroku fizyki fMaxDt = 0.01; //[s] początkowy krok czasowy fizyki @@ -221,34 +222,34 @@ bool TWorld::Init( GLFWwindow *Window ) { auto timestart = std::chrono::system_clock::now(); window = Window; - Global::window = Window; // do WM_COPYDATA - Global::pCamera = &Camera; // Ra: wskaźnik potrzebny do likwidacji drgań + Global.window = Window; // do WM_COPYDATA + Global.pCamera = &Camera; // Ra: wskaźnik potrzebny do likwidacji drgań - WriteLog( "\nStarting MaSzyna rail vehicle simulator (release: " + Global::asVersion + ")" ); + WriteLog( "\nStarting 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\n" ); UILayer.set_background( "logo" ); - glfwSetWindowTitle( window, ( Global::AppName + " (" + Global::SceneryFile + ")" ).c_str() ); // nazwa scenerii + glfwSetWindowTitle( window, ( Global.AppName + " (" + Global.SceneryFile + ")" ).c_str() ); // nazwa scenerii UILayer.set_progress(0.01); UILayer.set_progress( "Loading scenery / Wczytywanie scenerii" ); GfxRenderer.Render(); WriteLog( "World setup..." ); - if( false == simulation::State.deserialize( Global::SceneryFile ) ) { return false; } + if( false == simulation::State.deserialize( Global.SceneryFile ) ) { return false; } simulation::Time.init(); Environment.init(); - Camera.Init(Global::FreeCameraInit[0], Global::FreeCameraInitAngle[0]); + Camera.Init(Global.FreeCameraInit[0], Global.FreeCameraInitAngle[0]); UILayer.set_progress( "Preparing train / Przygotowanie kabiny" ); - WriteLog( "Player train init: " + Global::asHumanCtrlVehicle ); + WriteLog( "Player train init: " + Global.asHumanCtrlVehicle ); TDynamicObject *nPlayerTrain; - if( Global::asHumanCtrlVehicle != "ghostview" ) - nPlayerTrain = simulation::Vehicles.find( Global::asHumanCtrlVehicle ); + if( Global.asHumanCtrlVehicle != "ghostview" ) + nPlayerTrain = simulation::Vehicles.find( Global.asHumanCtrlVehicle ); if (nPlayerTrain) { Train = new TTrain(); @@ -258,7 +259,7 @@ bool TWorld::Init( GLFWwindow *Window ) { mvControlled = Controlled->ControlledFind()->MoverParameters; WriteLog("Player train init OK"); - glfwSetWindowTitle( window, ( Global::AppName + " (" + Controlled->MoverParameters->Name + " @ " + Global::SceneryFile + ")" ).c_str() ); + glfwSetWindowTitle( window, ( Global.AppName + " (" + Controlled->MoverParameters->Name + " @ " + Global.SceneryFile + ")" ).c_str() ); FollowView(); } @@ -273,7 +274,7 @@ bool TWorld::Init( GLFWwindow *Window ) { } else { - if (Global::asHumanCtrlVehicle != "ghostview") + if (Global.asHumanCtrlVehicle != "ghostview") { Error("Player train doesn't exist!"); } @@ -283,10 +284,10 @@ bool TWorld::Init( GLFWwindow *Window ) { mvControlled = NULL; Camera.Type = tp_Free; DebugCamera = Camera; - Global::DebugCameraPosition = DebugCamera.Pos; + Global.DebugCameraPosition = DebugCamera.Pos; } - // if (!Global::bMultiplayer) //na razie włączone + // if (!Global.bMultiplayer) //na razie włączone { // eventy aktywowane z klawiatury tylko dla jednego użytkownika KeyEvents[ 0 ] = simulation::Events.FindEvent( "keyctrl00" ); KeyEvents[ 1 ] = simulation::Events.FindEvent( "keyctrl01" ); @@ -317,10 +318,10 @@ bool TWorld::Init( GLFWwindow *Window ) { Timer::ResetTimers(); // make 4 empty lines for the ui header, to cut down on work down the road - UIHeader->text_lines.emplace_back( "", Global::UITextColor ); - UIHeader->text_lines.emplace_back( "", Global::UITextColor ); - UIHeader->text_lines.emplace_back( "", Global::UITextColor ); - UIHeader->text_lines.emplace_back( "", Global::UITextColor ); + UIHeader->text_lines.emplace_back( "", Global.UITextColor ); + UIHeader->text_lines.emplace_back( "", Global.UITextColor ); + UIHeader->text_lines.emplace_back( "", Global.UITextColor ); + UIHeader->text_lines.emplace_back( "", Global.UITextColor ); // bind the panels with ui object. maybe not the best place for this but, eh UILayer.push_back( UIHeader ); UILayer.push_back( UITable ); @@ -331,7 +332,7 @@ bool TWorld::Init( GLFWwindow *Window ) { void TWorld::OnKeyDown(int cKey) { // dump keypress info in the log - if( !Global::iPause ) { + if( !Global.iPause ) { // podczas pauzy klawisze nie działają std::string keyinfo; auto keyname = glfwGetKeyName( cKey, 0 ); @@ -366,9 +367,9 @@ void TWorld::OnKeyDown(int cKey) { if( keyinfo.empty() == false ) { std::string keymodifiers; - if( Global::shiftState ) + if( Global.shiftState ) keymodifiers += "[Shift]+"; - if( Global::ctrlState ) + if( Global.ctrlState ) keymodifiers += "[Ctrl]+"; WriteLog( "Key pressed: " + keymodifiers + "[" + keyinfo + "]" ); @@ -380,41 +381,41 @@ void TWorld::OnKeyDown(int cKey) { if( ( cKey >= GLFW_KEY_0 ) && ( cKey <= GLFW_KEY_9 ) ) // klawisze cyfrowe { int i = cKey - GLFW_KEY_0; // numer klawisza - if (Global::shiftState) { + if (Global.shiftState) { // z [Shift] uruchomienie eventu - if( ( false == Global::iPause ) // podczas pauzy klawisze nie działają + if( ( false == Global.iPause ) // podczas pauzy klawisze nie działają && ( KeyEvents[ i ] != nullptr ) ) { simulation::Events.AddToQuery( KeyEvents[ i ], NULL ); } } else // zapamiętywanie kamery może działać podczas pauzy if (FreeFlyModeFlag) // w trybie latania można przeskakiwać do ustawionych kamer - if( ( Global::iTextMode != GLFW_KEY_F12 ) && - ( Global::iTextMode != GLFW_KEY_F3 ) ) // ograniczamy użycie kamer + if( ( Global.iTextMode != GLFW_KEY_F12 ) && + ( Global.iTextMode != GLFW_KEY_F3 ) ) // ograniczamy użycie kamer { - if ((!Global::FreeCameraInit[i].x) - && (!Global::FreeCameraInit[i].y) - && (!Global::FreeCameraInit[i].z)) + if ((!Global.FreeCameraInit[i].x) + && (!Global.FreeCameraInit[i].y) + && (!Global.FreeCameraInit[i].z)) { // jeśli kamera jest w punkcie zerowym, zapamiętanie współrzędnych i kątów - Global::FreeCameraInit[i] = Camera.Pos; - Global::FreeCameraInitAngle[i].x = Camera.Pitch; - Global::FreeCameraInitAngle[i].y = Camera.Yaw; - Global::FreeCameraInitAngle[i].z = Camera.Roll; + Global.FreeCameraInit[i] = Camera.Pos; + Global.FreeCameraInitAngle[i].x = Camera.Pitch; + Global.FreeCameraInitAngle[i].y = Camera.Yaw; + Global.FreeCameraInitAngle[i].z = Camera.Roll; // logowanie, żeby można było do scenerii przepisać WriteLog( - "camera " + std::to_string( Global::FreeCameraInit[i].x ) + " " - + std::to_string(Global::FreeCameraInit[i].y ) + " " - + std::to_string(Global::FreeCameraInit[i].z ) + " " - + std::to_string(RadToDeg(Global::FreeCameraInitAngle[i].x)) + " " - + std::to_string(RadToDeg(Global::FreeCameraInitAngle[i].y)) + " " - + std::to_string(RadToDeg(Global::FreeCameraInitAngle[i].z)) + " " + "camera " + std::to_string( Global.FreeCameraInit[i].x ) + " " + + std::to_string(Global.FreeCameraInit[i].y ) + " " + + std::to_string(Global.FreeCameraInit[i].z ) + " " + + std::to_string(RadToDeg(Global.FreeCameraInitAngle[i].x)) + " " + + std::to_string(RadToDeg(Global.FreeCameraInitAngle[i].y)) + " " + + std::to_string(RadToDeg(Global.FreeCameraInitAngle[i].z)) + " " + std::to_string(i) + " endcamera"); } else // również przeskakiwanie - { // Ra: to z tą kamerą (Camera.Pos i Global::pCameraPosition) jest trochę bez sensu - Global::SetCameraPosition( Global::FreeCameraInit[i] ); // nowa pozycja dla generowania obiektów - Camera.Init(Global::FreeCameraInit[i], - Global::FreeCameraInitAngle[i]); // przestawienie + { // Ra: to z tą kamerą (Camera.Pos i Global.pCameraPosition) jest trochę bez sensu + Global.pCameraPosition = Global.FreeCameraInit[i]; // nowa pozycja dla generowania obiektów + Camera.Init(Global.FreeCameraInit[i], + Global.FreeCameraInitAngle[i]); // przestawienie } } // będzie jeszcze załączanie sprzęgów z [Ctrl] @@ -426,59 +427,59 @@ void TWorld::OnKeyDown(int cKey) { case GLFW_KEY_F1: { if( DebugModeFlag ) { // additional time speedup keys in debug mode - if( Global::ctrlState ) { + if( Global.ctrlState ) { // ctrl-f3 simulation::Time.update( 20.0 * 60.0 ); } - else if( Global::shiftState ) { + else if( Global.shiftState ) { // shift-f3 simulation::Time.update( 5.0 * 60.0 ); } } - if( ( false == Global::ctrlState ) - && ( false == Global::shiftState ) ) { + if( ( false == Global.ctrlState ) + && ( false == Global.shiftState ) ) { // czas i relacja - if( Global::iTextMode == cKey ) { ++Global::iScreenMode[ cKey - GLFW_KEY_F1 ]; } - if( Global::iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { + if( Global.iTextMode == cKey ) { ++Global.iScreenMode[ cKey - GLFW_KEY_F1 ]; } + if( Global.iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { // wyłączenie napisów - Global::iTextMode = 0; - Global::iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; + Global.iTextMode = 0; + Global.iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; } else { - Global::iTextMode = cKey; + Global.iTextMode = cKey; } } break; } case GLFW_KEY_F2: { // parametry pojazdu - if( Global::iTextMode == cKey ) { ++Global::iScreenMode[ cKey - GLFW_KEY_F1 ]; } - if( Global::iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { + if( Global.iTextMode == cKey ) { ++Global.iScreenMode[ cKey - GLFW_KEY_F1 ]; } + if( Global.iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { // wyłączenie napisów - Global::iTextMode = 0; - Global::iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; + Global.iTextMode = 0; + Global.iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; } else { - Global::iTextMode = cKey; + Global.iTextMode = cKey; } break; } case GLFW_KEY_F3: { // timetable - if( Global::iTextMode == cKey ) { ++Global::iScreenMode[ cKey - GLFW_KEY_F1 ]; } - if( Global::iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { + if( Global.iTextMode == cKey ) { ++Global.iScreenMode[ cKey - GLFW_KEY_F1 ]; } + if( Global.iScreenMode[ cKey - GLFW_KEY_F1 ] > 1 ) { // wyłączenie napisów - Global::iTextMode = 0; - Global::iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; + Global.iTextMode = 0; + Global.iScreenMode[ cKey - GLFW_KEY_F1 ] = 0; } else { - Global::iTextMode = cKey; + Global.iTextMode = cKey; } break; } case GLFW_KEY_F4: { - InOutKey( !Global::shiftState ); // distant view with Shift, short distance step out otherwise + InOutKey( !Global.shiftState ); // distant view with Shift, short distance step out otherwise break; } case GLFW_KEY_F5: { @@ -488,7 +489,7 @@ void TWorld::OnKeyDown(int cKey) { break; } - TDynamicObject *tmp = std::get( simulation::Region->find_vehicle( Global::pCameraPosition, 50, true, false ) ); + TDynamicObject *tmp = std::get( simulation::Region->find_vehicle( Global.pCameraPosition, 50, true, false ) ); if( ( tmp != nullptr ) && ( tmp != Controlled ) ) { @@ -510,22 +511,22 @@ void TWorld::OnKeyDown(int cKey) { } else SafeDelete( Train ); // i nie ma czym sterować - // Global::pUserDynamic=Controlled; //renerowanie pojazdu względem kabiny - // Global::iTextMode=VK_F4; + // Global.pUserDynamic=Controlled; //renerowanie pojazdu względem kabiny + // Global.iTextMode=VK_F4; if( Train ) InOutKey(); // do kabiny } } -// Global::iTextMode = cKey; +// Global.iTextMode = cKey; break; } case GLFW_KEY_F6: { -// Global::iTextMode = cKey; +// Global.iTextMode = cKey; // przyspieszenie symulacji do testowania scenerii... uwaga na FPS! if( DebugModeFlag ) { - if( Global::ctrlState ) { Global::fTimeSpeed = ( Global::shiftState ? 60.0 : 20.0 ); } - else { Global::fTimeSpeed = ( Global::shiftState ? 5.0 : 1.0 ); } + if( Global.ctrlState ) { Global.fTimeSpeed = ( Global.shiftState ? 60.0 : 20.0 ); } + else { Global.fTimeSpeed = ( Global.shiftState ? 5.0 : 1.0 ); } } break; } @@ -533,15 +534,15 @@ void TWorld::OnKeyDown(int cKey) { // debug mode functions if( DebugModeFlag ) { - if( Global::ctrlState ) { + if( Global.ctrlState ) { // ctrl + f7 toggles static daylight ToggleDaylight(); break; } else { // f7: wireframe toggle - Global::bWireFrame = !Global::bWireFrame; - if( true == Global::bWireFrame ) { + Global.bWireFrame = !Global.bWireFrame; + if( true == Global.bWireFrame ) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { @@ -552,88 +553,88 @@ void TWorld::OnKeyDown(int cKey) { break; } case GLFW_KEY_F8: { - if( Global::ctrlState - && Global::shiftState ) { + if( Global.ctrlState + && Global.shiftState ) { DebugCameraFlag = !DebugCameraFlag; // taka opcjonalna funkcja, może się czasem przydać } else { - Global::iTextMode = cKey; + Global.iTextMode = cKey; } break; } case GLFW_KEY_F9: { - Global::iTextMode = cKey; + Global.iTextMode = cKey; // wersja break; } case GLFW_KEY_F10: { - if( Global::iTextMode == cKey ) { - Global::iTextMode = - ( Global::iPause && ( cKey != GLFW_KEY_F1 ) ? + if( Global.iTextMode == cKey ) { + Global.iTextMode = + ( Global.iPause && ( cKey != GLFW_KEY_F1 ) ? GLFW_KEY_F1 : 0 ); // wyłączenie napisów, chyba że pauza } else { - Global::iTextMode = cKey; + Global.iTextMode = cKey; } break; } case GLFW_KEY_F12: { // coś tam jeszcze - if( Global::ctrlState - && Global::shiftState ) + if( Global.ctrlState + && Global.shiftState ) DebugModeFlag = !DebugModeFlag; // taka opcjonalna funkcja, może się czasem przydać else - Global::iTextMode = cKey; + Global.iTextMode = cKey; break; } } // if (cKey!=VK_F4) return; // nie są przekazywane do pojazdu wcale } - if( Global::iTextMode == GLFW_KEY_F10 ) // wyświetlone napisy klawiszem F10 + if( Global.iTextMode == GLFW_KEY_F10 ) // wyświetlone napisy klawiszem F10 { // i potwierdzenie if( cKey == GLFW_KEY_Y ) { // flaga wyjścia z programu ::PostQuitMessage( 0 ); -// Global::iTextMode = -1; +// Global.iTextMode = -1; } return; // nie przekazujemy do pociągu } - else if ((Global::iTextMode == GLFW_KEY_F12) ? (cKey >= '0') && (cKey <= '9') : false) + else if ((Global.iTextMode == GLFW_KEY_F12) ? (cKey >= '0') && (cKey <= '9') : false) { // tryb konfiguracji debugmode (przestawianie kamery już wyłączone - if (!Global::shiftState) // bez [Shift] + if (!Global.shiftState) // bez [Shift] { if (cKey == GLFW_KEY_1) - Global::iWriteLogEnabled ^= 1; // włącz/wyłącz logowanie do pliku + Global.iWriteLogEnabled ^= 1; // włącz/wyłącz logowanie do pliku else if (cKey == GLFW_KEY_2) { // włącz/wyłącz okno konsoli - Global::iWriteLogEnabled ^= 2; - if ((Global::iWriteLogEnabled & 2) == 0) // nie było okienka + Global.iWriteLogEnabled ^= 2; + if ((Global.iWriteLogEnabled & 2) == 0) // nie było okienka { // otwarcie okna AllocConsole(); // jeśli konsola już jest, to zwróci błąd; uwalniać nie ma po // co, bo się odłączy SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN); } } - // else if (cKey=='3') Global::iWriteLogEnabled^=4; //wypisywanie nazw torów + // else if (cKey=='3') Global.iWriteLogEnabled^=4; //wypisywanie nazw torów } } else if( cKey == GLFW_KEY_ESCAPE ) { // toggle pause - if( Global::iPause & 1 ) // jeśli pauza startowa - Global::iPause &= ~1; // odpauzowanie, gdy po wczytaniu miało nie startować - else if( !( Global::iMultiplayer & 2 ) ) // w multiplayerze pauza nie ma sensu - Global::iPause ^= 2; // zmiana stanu zapauzowania - if( Global::iPause ) {// jak pauza - Global::iTextMode = GLFW_KEY_F1; // to wyświetlić zegar i informację + if( Global.iPause & 1 ) // jeśli pauza startowa + Global.iPause &= ~1; // odpauzowanie, gdy po wczytaniu miało nie startować + else if( !( Global.iMultiplayer & 2 ) ) // w multiplayerze pauza nie ma sensu + Global.iPause ^= 2; // zmiana stanu zapauzowania + if( Global.iPause ) {// jak pauza + Global.iTextMode = GLFW_KEY_F1; // to wyświetlić zegar i informację } } else { if( ( true == DebugModeFlag ) - && ( false == Global::shiftState ) - && ( true == Global::ctrlState ) + && ( false == Global.shiftState ) + && ( true == Global.ctrlState ) && ( Controlled != nullptr ) && ( Controlled->Controller == Humandriver ) ) { @@ -690,7 +691,7 @@ void TWorld::InOutKey( bool const Near ) DistantView( Near ); } DebugCamera = Camera; - Global::DebugCameraPosition = DebugCamera.Pos; + Global.DebugCameraPosition = DebugCamera.Pos; } else { // jazda w kabinie @@ -698,7 +699,7 @@ void TWorld::InOutKey( bool const Near ) { Train->Dynamic()->bDisplayCab = true; Train->Dynamic()->ABuSetModelShake( - vector3(0, 0, 0)); // zerowanie przesunięcia przed powrotem? + Math3D::vector3(0, 0, 0)); // zerowanie przesunięcia przed powrotem? // Camera.Stop(); //zatrzymanie ruchu Train->MechStop(); FollowView(); // na pozycję mecha @@ -709,13 +710,13 @@ void TWorld::InOutKey( bool const Near ) // update window title to reflect the situation glfwSetWindowTitle( window, - ( Global::AppName + ( Global.AppName + " (" + ( Controlled != nullptr ? Controlled->MoverParameters->Name : "" ) + " @ " - + Global::SceneryFile + + Global.SceneryFile + ")" ).c_str() ); }; @@ -738,16 +739,16 @@ void TWorld::DistantView( bool const Near ) if( true == Near ) { Camera.Pos = - vector3( Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z ) + Math3D::vector3( Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z ) + left * vehicle->GetWidth() - + vector3( 1.25 * left.x, 1.6, 1.25 * left.z ); + + Math3D::vector3( 1.25 * left.x, 1.6, 1.25 * left.z ); } else { Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * vehicle->MoverParameters->ActiveCab * 50.0 - + vector3( -10.0 * left.x, 1.6, -10.0 * left.z ); + + Math3D::vector3( -10.0 * left.x, 1.6, -10.0 * left.z ); } Camera.LookAt = vehicle->GetPosition(); @@ -765,13 +766,13 @@ void TWorld::FollowView(bool wycisz) { { // jeżeli poza kabiną, przestawiamy w jej okolicę - OK if( Train ) { // wyłączenie trzęsienia na siłę? - Train->Dynamic()->ABuSetModelShake( vector3() ); + Train->Dynamic()->ABuSetModelShake( {} ); } DistantView(); // przestawienie kamery //żeby nie bylo numerów z 'fruwajacym' lokiem - konsekwencja bujania pudła // tu ustawić nową, bo od niej liczą się odległości - Global::SetCameraPosition( Camera.Pos ); + Global.pCameraPosition = Camera.Pos; } else if (Train) { // korekcja ustawienia w kabinie - OK @@ -804,22 +805,22 @@ void TWorld::FollowView(bool wycisz) { bool TWorld::Update() { - Timer::UpdateTimers(Global::iPause != 0); + Timer::UpdateTimers(Global.iPause != 0); Timer::subsystem.sim_total.start(); - if( (Global::iPause == 0) + if( (Global.iPause == 0) || (m_init == false) ) { // jak pauza, to nie ma po co tego przeliczać simulation::Time.update( Timer::GetDeltaTime() ); // Ra 2014-07: przeliczenie kąta czasu (do animacji zależnych od czasu) auto const &time = simulation::Time.data(); - Global::fTimeAngleDeg = time.wHour * 15.0 + time.wMinute * 0.25 + ( ( time.wSecond + 0.001 * time.wMilliseconds ) / 240.0 ); - Global::fClockAngleDeg[ 0 ] = 36.0 * ( time.wSecond % 10 ); // jednostki sekund - Global::fClockAngleDeg[ 1 ] = 36.0 * ( time.wSecond / 10 ); // dziesiątki sekund - Global::fClockAngleDeg[ 2 ] = 36.0 * ( time.wMinute % 10 ); // jednostki minut - Global::fClockAngleDeg[ 3 ] = 36.0 * ( time.wMinute / 10 ); // dziesiątki minut - Global::fClockAngleDeg[ 4 ] = 36.0 * ( time.wHour % 10 ); // jednostki godzin - Global::fClockAngleDeg[ 5 ] = 36.0 * ( time.wHour / 10 ); // dziesiątki godzin + Global.fTimeAngleDeg = time.wHour * 15.0 + time.wMinute * 0.25 + ( ( time.wSecond + 0.001 * time.wMilliseconds ) / 240.0 ); + Global.fClockAngleDeg[ 0 ] = 36.0 * ( time.wSecond % 10 ); // jednostki sekund + Global.fClockAngleDeg[ 1 ] = 36.0 * ( time.wSecond / 10 ); // dziesiątki sekund + Global.fClockAngleDeg[ 2 ] = 36.0 * ( time.wMinute % 10 ); // jednostki minut + Global.fClockAngleDeg[ 3 ] = 36.0 * ( time.wMinute / 10 ); // dziesiątki minut + Global.fClockAngleDeg[ 4 ] = 36.0 * ( time.wHour % 10 ); // jednostki godzin + Global.fClockAngleDeg[ 5 ] = 36.0 * ( time.wHour / 10 ); // dziesiątki godzin Update_Environment(); } // koniec działań niewykonywanych podczas pauzy @@ -837,7 +838,7 @@ bool TWorld::Update() { { // Ra: czas dla fizyki jest skwantowany - fizykę lepiej przeliczać stałym krokiem // tak można np. moc silników itp., ale ruch musi być przeliczany w każdej klatce, bo // inaczej skacze - Global::tranTexts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie + Global.tranTexts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie Console::Update(); // obsługa cykli PoKeys (np. aktualizacja wyjść analogowych) double iter = ceil(fTimeBuffer / fMaxDt); // ile kroków się zmieściło od ostatniego sprawdzania? @@ -880,7 +881,7 @@ bool TWorld::Update() { // NOTE: experimentally changing this to prevent the desync. // TODO: test what happens if we hit more than 20 * 0.01 sec slices, i.e. less than 5 fps Timer::subsystem.sim_dynamics.start(); - if( true == Global::FullPhysics ) { + if( true == Global.FullPhysics ) { // mixed calculation mode, steps calculated in ~0.05s chunks while( updatecount >= 5 ) { simulation::State.update( stepdeltatime, 5 ); @@ -899,13 +900,13 @@ bool TWorld::Update() { // secondary fixed step simulation time routines while( m_secondaryupdateaccumulator >= m_secondaryupdaterate ) { - Global::tranTexts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie + ui::Transcripts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie // awaria PoKeys mogła włączyć pauzę - przekazać informację - if( Global::iMultiplayer ) // dajemy znać do serwera o wykonaniu - if( iPause != Global::iPause ) { // przesłanie informacji o pauzie do programu nadzorującego + if( Global.iMultiplayer ) // dajemy znać do serwera o wykonaniu + if( iPause != Global.iPause ) { // przesłanie informacji o pauzie do programu nadzorującego multiplayer::WyslijParam( 5, 3 ); // ramka 5 z czasem i stanem zapauzowania - iPause = Global::iPause; + iPause = Global.iPause; } // fixed step part of the camera update @@ -921,7 +922,7 @@ bool TWorld::Update() { // variable step simulation time routines - if( Global::changeDynObj ) { + if( Global.changeDynObj ) { // ABu zmiana pojazdu - przejście do innego ChangeDynamic(); } @@ -982,7 +983,7 @@ bool TWorld::Update() { void TWorld::Update_Camera( double const Deltatime ) { - if( false == Global::ControlPicking ) { + if( false == Global.ControlPicking ) { if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS ) { Camera.Reset(); // likwidacja obrotów - patrzy horyzontalnie na południe if( Controlled && LengthSquared3( Controlled->GetPosition() - Camera.Pos ) < ( 1500 * 1500 ) ) { @@ -990,9 +991,9 @@ TWorld::Update_Camera( double const Deltatime ) { Camera.LookAt = Controlled->GetPosition(); } else { - TDynamicObject *d = std::get( simulation::Region->find_vehicle( Global::pCameraPosition, 300, false, false ) ); + TDynamicObject *d = std::get( simulation::Region->find_vehicle( Global.pCameraPosition, 300, false, false ) ); if( !d ) - d = std::get( simulation::Region->find_vehicle( Global::pCameraPosition, 1000, false, false ) ); // dalej szukanie, jesli bliżej nie ma + d = std::get( simulation::Region->find_vehicle( Global.pCameraPosition, 1000, false, false ) ); // dalej szukanie, jesli bliżej nie ma if( d && pDynamicNearest ) { // jeśli jakiś jest znaleziony wcześniej @@ -1014,40 +1015,40 @@ TWorld::Update_Camera( double const Deltatime ) { } else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) == GLFW_PRESS ) { // middle mouse button controls zoom. - Global::ZoomFactor = std::min( 4.5f, Global::ZoomFactor + 15.0f * static_cast( Deltatime ) ); + Global.ZoomFactor = std::min( 4.5f, Global.ZoomFactor + 15.0f * static_cast( Deltatime ) ); } else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) != GLFW_PRESS ) { // reset zoom level if the button is no longer held down. // NOTE: yes, this is terrible way to go about it. it'll do for now. - Global::ZoomFactor = std::max( 1.0f, Global::ZoomFactor - 15.0f * static_cast( Deltatime ) ); + Global.ZoomFactor = std::max( 1.0f, Global.ZoomFactor - 15.0f * static_cast( Deltatime ) ); } } if( DebugCameraFlag ) { DebugCamera.Update(); } else { Camera.Update(); } // uwzględnienie ruchu wywołanego klawiszami // reset window state, it'll be set again if applicable in a check below - Global::CabWindowOpen = false; + Global.CabWindowOpen = false; if( ( Train != nullptr ) && ( Camera.Type == tp_Follow ) && ( false == DebugCameraFlag ) ) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery - vector3 tempangle = Controlled->VectorFront() * ( Controlled->MoverParameters->ActiveCab == -1 ? -1 : 1 ); + auto tempangle = Controlled->VectorFront() * ( Controlled->MoverParameters->ActiveCab == -1 ? -1 : 1 ); double modelrotate = atan2( -tempangle.x, tempangle.z ); - if( (Global::ctrlState) - && ( (Console::Pressed( Global::Keys[ k_MechLeft ]) - || (Console::Pressed( Global::Keys[ k_MechRight ]))))) { + if( ( true == Global.ctrlState ) + && ( ( glfwGetKey( Global.window, GLFW_KEY_LEFT ) == GLFW_TRUE ) + || ( glfwGetKey( Global.window, GLFW_KEY_RIGHT ) == GLFW_TRUE ) ) ) { // jeśli lusterko lewe albo prawe (bez rzucania na razie) - Global::CabWindowOpen = true; + Global.CabWindowOpen = true; - bool lr = Console::Pressed( Global::Keys[ k_MechLeft ] ); + auto const lr { glfwGetKey( Global.window, GLFW_KEY_LEFT ) == GLFW_TRUE }; // Camera.Yaw powinno być wyzerowane, aby po powrocie patrzeć do przodu Camera.Pos = Controlled->GetPosition() + Train->MirrorPosition( lr ); // pozycja lusterka Camera.Yaw = 0; // odchylenie na bok od Camera.LookAt if( Train->Dynamic()->MoverParameters->ActiveCab == 0 ) Camera.LookAt = Camera.Pos - Train->GetDirection(); // gdy w korytarzu - else if( Global::shiftState ) { + else if( Global.shiftState ) { // patrzenie w bok przez szybę Camera.LookAt = Camera.Pos - ( lr ? -1 : 1 ) * Train->Dynamic()->VectorLeft() * Train->Dynamic()->MoverParameters->ActiveCab; } @@ -1062,7 +1063,7 @@ TWorld::Update_Camera( double const Deltatime ) { else { // patrzenie standardowe Camera.Pos = Train->GetWorldMechPosition(); // Train.GetPosition1(); - if( !Global::iPause ) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami + if( !Global.iPause ) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami Camera.Roll = atan( Train->pMechShake.x * Train->fMechRoll ); // hustanie kamery na boki Camera.Pitch -= 0.5 * atan( Train->vMechVelocity.z * Train->fMechPitch ); // hustanie kamery przod tyl //Ra: tu // jest uciekanie kamery w górę!!! @@ -1092,8 +1093,8 @@ TWorld::Update_Camera( double const Deltatime ) { // kamera nieruchoma } // all done, update camera position to the new value - Global::pCameraPosition = Camera.Pos; - Global::DebugCameraPosition = DebugCamera.Pos; + Global.pCameraPosition = Camera.Pos; + Global.DebugCameraPosition = DebugCamera.Pos; } void TWorld::Update_Environment() { @@ -1126,7 +1127,7 @@ TWorld::Update_UI() { UILayer.set_tooltip( ( cabcontrol ? cabcontrol->pName : "" ) ); } } - if( ( true == Global::ControlPicking ) && ( true == FreeFlyModeFlag ) && ( true == DebugModeFlag ) ) { + if( ( true == Global.ControlPicking ) && ( true == FreeFlyModeFlag ) && ( true == DebugModeFlag ) ) { auto const scenerynode = GfxRenderer.Pick_Node(); UILayer.set_tooltip( ( scenerynode ? @@ -1134,7 +1135,7 @@ TWorld::Update_UI() { "" ) ); } - switch( Global::iTextMode ) { + switch( Global.iTextMode ) { case( GLFW_KEY_F1 ) : { // f1, default mode: current time and timetable excerpt @@ -1144,7 +1145,7 @@ TWorld::Update_UI() { + to_string( time.wHour ) + ":" + ( time.wMinute < 10 ? "0" : "" ) + to_string( time.wMinute ) + ":" + ( time.wSecond < 10 ? "0" : "" ) + to_string( time.wSecond ); - if( Global::iPause ) { + if( Global.iPause ) { uitextline1 += " (paused)"; } @@ -1170,7 +1171,7 @@ TWorld::Update_UI() { "!SHP! " : " " ); - if( Global::iScreenMode[ Global::iTextMode - GLFW_KEY_F1 ] == 1 ) { + if( Global.iScreenMode[ Global.iTextMode - GLFW_KEY_F1 ] == 1 ) { // detail mode on second key press uitextline2 += " Speed: " + std::to_string( static_cast( std::floor( mover->Vel ) ) ) + " km/h" @@ -1215,26 +1216,26 @@ TWorld::Update_UI() { + to_string( time.wHour ) + ":" + ( time.wMinute < 10 ? "0" : "" ) + to_string( time.wMinute ) + ":" + ( time.wSecond < 10 ? "0" : "" ) + to_string( time.wSecond ); - if( Global::iPause ) { + if( Global.iPause ) { uitextline1 += " (paused)"; } - uitextline2 = Global::Bezogonkow( owner->Relation(), true ) + " (" + Global::Bezogonkow( owner->Timetable()->TrainName, true ) + ")"; - auto const nextstation = Global::Bezogonkow( owner->NextStop(), true ); + uitextline2 = Bezogonkow( owner->Relation(), true ) + " (" + Bezogonkow( owner->Timetable()->TrainName, true ) + ")"; + auto const nextstation = Bezogonkow( owner->NextStop(), true ); if( !nextstation.empty() ) { // jeśli jest podana relacja, to dodajemy punkt następnego zatrzymania uitextline3 = " -> " + nextstation; } - if( Global::iScreenMode[ Global::iTextMode - GLFW_KEY_F1 ] == 1 ) { + if( Global.iScreenMode[ Global.iTextMode - GLFW_KEY_F1 ] == 1 ) { if( 0 == table->StationCount ) { // only bother if there's stations to list - UITable->text_lines.emplace_back( "(no timetable)", Global::UITextColor ); + UITable->text_lines.emplace_back( "(no timetable)", Global.UITextColor ); } else { // header - UITable->text_lines.emplace_back( "+----------------------------+-------+-------+-----+", Global::UITextColor ); + UITable->text_lines.emplace_back( "+----------------------------+-------+-------+-----+", Global.UITextColor ); TMTableLine *tableline; for( int i = owner->iStationStart; i <= std::min( owner->iStationStart + 15, table->StationCount ); ++i ) { @@ -1257,14 +1258,14 @@ TWorld::Update_UI() { vmax = vmax.substr( vmax.length() - 3, 3 ); // z wyrównaniem do prawej UITable->text_lines.emplace_back( - Global::Bezogonkow( "| " + station + " | " + arrival + " | " + departure + " | " + vmax + " | " + tableline->StationWare, true ), + Bezogonkow( "| " + station + " | " + arrival + " | " + departure + " | " + vmax + " | " + tableline->StationWare, true ), ( ( owner->iStationStart < table->StationIndex ) && ( i < table->StationIndex ) && ( ( time.wHour * 60 + time.wMinute ) >= ( tableline->Dh * 60 + tableline->Dm ) ) ? float4( 0.0f, 1.0f, 0.0f, 1.0f ) :// czas minął i odjazd był, to nazwa stacji będzie na zielono - Global::UITextColor ) ); + Global.UITextColor ) ); // divider/footer - UITable->text_lines.emplace_back( "+----------------------------+-------+-------+-----+", Global::UITextColor ); + UITable->text_lines.emplace_back( "+----------------------------+-------+-------+-----+", Global.UITextColor ); } } } @@ -1433,17 +1434,14 @@ TWorld::Update_UI() { if( ( vehicle->Mechanik->VelNext == 0.0 ) && ( vehicle->Mechanik->eSignNext ) ) { // jeśli ma zapamiętany event semafora, nazwa eventu semafora - uitextline4 += - " (" - + Global::Bezogonkow( vehicle->Mechanik->eSignNext->asName ) - + ")"; + uitextline4 += " (" + Bezogonkow( vehicle->Mechanik->eSignNext->asName ) + ")"; } // biezaca komenda dla AI uitextline4 += ", command: " + vehicle->Mechanik->OrderCurrent(); } - if( Global::iScreenMode[ Global::iTextMode - GLFW_KEY_F1 ] == 1 ) { + if( Global.iScreenMode[ Global.iTextMode - GLFW_KEY_F1 ] == 1 ) { // f2 screen, track scan mode if( vehicle->Mechanik == nullptr ) { //żeby była tabelka, musi być AI @@ -1454,7 +1452,7 @@ TWorld::Update_UI() { do { std::string scanline = vehicle->Mechanik->TableText( i ); if( scanline.empty() ) { break; } - UITable->text_lines.emplace_back( Global::Bezogonkow( scanline ), Global::UITextColor ); + UITable->text_lines.emplace_back( Bezogonkow( scanline ), Global.UITextColor ); ++i; } while( i < speedtablesize ); // TController:iSpeedTableSize TODO: change when the table gets recoded } @@ -1472,8 +1470,8 @@ TWorld::Update_UI() { + std::string( "S SEE NEN NWW SW" ) .substr( 0 + 2 * floor( fmod( 8 + ( Camera.Yaw + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ), 2 ); // current luminance level - uitextline2 = "Light level: " + to_string( Global::fLuminance, 3 ); - if( Global::FakeLight ) { uitextline2 += "(*)"; } + uitextline2 = "Light level: " + to_string( Global.fLuminance, 3 ); + if( Global.FakeLight ) { uitextline2 += "(*)"; } } break; @@ -1482,25 +1480,25 @@ TWorld::Update_UI() { case( GLFW_KEY_F8 ) : { // gfx renderer data uitextline1 = - "FoV: " + to_string( Global::FieldOfView / Global::ZoomFactor, 1 ) - + ", Draw range x " + to_string( Global::fDistanceFactor, 1 ) + "FoV: " + to_string( Global.FieldOfView / Global.ZoomFactor, 1 ) + + ", Draw range x " + to_string( Global.fDistanceFactor, 1 ) // + "; sectors: " + std::to_string( GfxRenderer.m_drawcount ) // + ", FPS: " + to_string( Timer::GetFPS(), 2 ); + ", FPS: " + std::to_string( static_cast(std::round(GfxRenderer.Framerate())) ); - if( Global::iSlowMotion ) { - uitextline1 += " (slowmotion " + to_string( Global::iSlowMotion ) + ")"; + if( Global.iSlowMotion ) { + uitextline1 += " (slowmotion " + to_string( Global.iSlowMotion ) + ")"; } uitextline2 = std::string( "Rendering mode: " ) - + ( Global::bUseVBO ? + + ( Global.bUseVBO ? "VBO" : "Display Lists" ) + " "; - if( false == Global::LastGLError.empty() ) { + if( false == Global.LastGLError.empty() ) { uitextline2 += "Last openGL error: " - + Global::LastGLError; + + Global.LastGLError; } // renderer stats uitextline3 = GfxRenderer.info_times(); @@ -1511,8 +1509,8 @@ TWorld::Update_UI() { case( GLFW_KEY_F9 ) : { // informacja o wersji - uitextline1 = "MaSzyna " + Global::asVersion; // informacja o wersji - if( Global::iMultiplayer ) { + uitextline1 = "MaSzyna " + Global.asVersion; // informacja o wersji + if( Global.iMultiplayer ) { uitextline1 += " (multiplayer mode is active)"; } uitextline3 = @@ -1532,8 +1530,8 @@ TWorld::Update_UI() { case( GLFW_KEY_F12 ) : { // opcje włączenia i wyłączenia logowania uitextline1 = "[0] Debugmode " + std::string( DebugModeFlag ? "(on)" : "(off)" ); - uitextline2 = "[1] log.txt " + std::string( ( Global::iWriteLogEnabled & 1 ) ? "(on)" : "(off)" ); - uitextline3 = "[2] Console " + std::string( ( Global::iWriteLogEnabled & 2 ) ? "(on)" : "(off)" ); + uitextline2 = "[1] log.txt " + std::string( ( Global.iWriteLogEnabled & 1 ) ? "(on)" : "(off)" ); + uitextline3 = "[2] Console " + std::string( ( Global.iWriteLogEnabled & 2 ) ? "(on)" : "(off)" ); break; } @@ -1650,7 +1648,7 @@ TWorld::Update_UI() { // induction motor data if( vehicle->MoverParameters->EngineType == ElectricInductionMotor ) { - UITable->text_lines.emplace_back( " eimc: eimv: press:", Global::UITextColor ); + UITable->text_lines.emplace_back( " eimc: eimv: press:", Global.UITextColor ); for( int i = 0; i <= 20; ++i ) { std::string parameters = @@ -1668,42 +1666,42 @@ TWorld::Update_UI() { parameters += " | " + vehicle->MED_labels[ i - 13 ] + to_string( vehicle->MED[ 0 ][ i - 13 ], 2, 9 ); } - UITable->text_lines.emplace_back( parameters, Global::UITextColor ); + UITable->text_lines.emplace_back( parameters, Global.UITextColor ); } } if (vehicle->MoverParameters->EngineType == DieselEngine) { std::string parameters = "param value"; - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "efill: " + to_string(vehicle->MoverParameters->dizel_fill, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "etorq: " + to_string(vehicle->MoverParameters->dizel_Torque, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "creal: " + to_string(vehicle->MoverParameters->dizel_engage, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "cdesi: " + to_string(vehicle->MoverParameters->dizel_engagestate, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "cdelt: " + to_string(vehicle->MoverParameters->dizel_engagedeltaomega, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "gears: " + to_string(vehicle->MoverParameters->dizel_automaticgearstatus, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hydro value"; - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCnI: " + to_string(vehicle->MoverParameters->hydro_TC_nIn, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCnO: " + to_string(vehicle->MoverParameters->hydro_TC_nOut, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCTM: " + to_string(vehicle->MoverParameters->hydro_TC_TMRatio, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCTI: " + to_string(vehicle->MoverParameters->hydro_TC_TorqueIn, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCTO: " + to_string(vehicle->MoverParameters->hydro_TC_TorqueOut, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCfl: " + to_string(vehicle->MoverParameters->hydro_TC_Fill, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); parameters = "hTCLR: " + to_string(vehicle->MoverParameters->hydro_TC_LockupRate, 2, 9); - UITable->text_lines.emplace_back(parameters, Global::UITextColor); + UITable->text_lines.emplace_back(parameters, Global.UITextColor); //parameters = "hTCXX: " + to_string(vehicle->MoverParameters->hydro_TC_nIn, 2, 9); - //UITable->text_lines.emplace_back(parameters, Global::UITextColor); + //UITable->text_lines.emplace_back(parameters, Global.UITextColor); } } // if( DebugModeFlag && Controlled ) @@ -1713,7 +1711,7 @@ TWorld::Update_UI() { } #ifdef EU07_USE_OLD_UI_CODE - if( Controlled && DebugModeFlag && !Global::iTextMode ) { + if( Controlled && DebugModeFlag && !Global.iTextMode ) { uitextline1 += ( "; d_omega " ) + to_string( Controlled->MoverParameters->dizel_engagedeltaomega, 3 ); @@ -1740,9 +1738,9 @@ TWorld::Update_UI() { // stenogramy dźwięków (ukryć, gdy tabelka skanowania lub rozkład?) auto &transcripts = UITranscripts->text_lines; transcripts.clear(); - for( auto const &transcript : Global::tranTexts.aLines ) { + for( auto const &transcript : ui::Transcripts.aLines ) { - if( Global::fTimeAngleDeg >= transcript.fShow ) { + if( Global.fTimeAngleDeg >= transcript.fShow ) { cParser parser( transcript.asText ); while( true == parser.getTokens( 1, false, "|" ) ) { @@ -1762,18 +1760,18 @@ void TWorld::OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) { case 0: // odesłanie identyfikatora wersji CommLog( Now() + " " + std::to_string(pRozkaz->iComm) + " version" + " rcvd"); - multiplayer::WyslijString(Global::asVersion, 0); // przedsatwienie się + multiplayer::WyslijString(Global.asVersion, 0); // przedsatwienie się break; case 1: // odesłanie identyfikatora wersji CommLog( Now() + " " + std::to_string(pRozkaz->iComm) + " scenery" + " rcvd"); - multiplayer::WyslijString(Global::SceneryFile, 1); // nazwa scenerii + multiplayer::WyslijString(Global.SceneryFile, 1); // nazwa scenerii break; case 2: { // event CommLog( Now() + " " + std::to_string( pRozkaz->iComm ) + " " + std::string( pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) ) + " rcvd" ); - if( Global::iMultiplayer ) { + if( Global.iMultiplayer ) { auto *event = simulation::Events.FindEvent( std::string( pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) ) ); if( event != nullptr ) { if( ( event->Type == tp_Multiple ) @@ -1787,7 +1785,7 @@ void TWorld::OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) break; } case 3: // rozkaz dla AI - if (Global::iMultiplayer) + if (Global.iMultiplayer) { int i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) CommLog( @@ -1827,20 +1825,20 @@ void TWorld::OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) { double t = pRozkaz->fPar[1]; simulation::Time.data().wDay = std::floor(t); // niby nie powinno być dnia, ale... - if (Global::fMoveLight >= 0) - Global::fMoveLight = t; // trzeba by deklinację Słońca przeliczyć + if (Global.fMoveLight >= 0) + Global.fMoveLight = t; // trzeba by deklinację Słońca przeliczyć simulation::Time.data().wHour = std::floor(24 * t) - 24.0 * simulation::Time.data().wDay; simulation::Time.data().wMinute = std::floor(60 * 24 * t) - 60.0 * (24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour); simulation::Time.data().wSecond = std::floor( 60 * 60 * 24 * t ) - 60.0 * ( 60.0 * ( 24.0 * simulation::Time.data().wDay + simulation::Time.data().wHour ) + simulation::Time.data().wMinute ); } if (*pRozkaz->iPar & 2) { // ustawienie flag zapauzowania - Global::iPause = pRozkaz->fPar[2]; // zakładamy, że wysyłający wie, co robi + Global.iPause = pRozkaz->fPar[2]; // zakładamy, że wysyłający wie, co robi } } break; case 6: // pobranie parametrów ruchu pojazdu - if (Global::iMultiplayer) { + if (Global.iMultiplayer) { // Ra 2014-12: to ma działać również dla pojazdów bez obsady CommLog( Now() + " " @@ -1851,7 +1849,7 @@ void TWorld::OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) // jeśli długość nazwy jest niezerowa szukamy pierwszego pojazdu o takiej nazwie i odsyłamy parametry ramką #7 auto *vehicle = ( pRozkaz->cString[ 1 ] == '*' ? - simulation::Vehicles.find( Global::asHumanCtrlVehicle ) : + simulation::Vehicles.find( Global.asHumanCtrlVehicle ) : simulation::Vehicles.find( std::string{ pRozkaz->cString + 1, (unsigned)pRozkaz->cString[ 0 ] } ) ); if( vehicle != nullptr ) { multiplayer::WyslijNamiary( vehicle ); // wysłanie informacji o pojeździe @@ -1892,7 +1890,7 @@ void TWorld::OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) { // szukamy pierwszego pojazdu o takiej nazwie i odsyłamy parametry ramką #13 auto *lookup = ( pRozkaz->cString[ 2 ] == '*' ? - simulation::Vehicles.find( Global::asHumanCtrlVehicle ) : // nazwa pojazdu użytkownika + simulation::Vehicles.find( Global.asHumanCtrlVehicle ) : // nazwa pojazdu użytkownika simulation::Vehicles.find( std::string( pRozkaz->cString + 2, (unsigned)pRozkaz->cString[ 1 ] ) ) ); // nazwa pojazdu if( lookup == nullptr ) { break; } // nothing found, nothing to do auto *d { lookup }; @@ -2007,11 +2005,11 @@ void TWorld::CreateE3D(std::string const &Path, bool Dynamic) } } // z powrotem defaultowa sciezka do tekstur - Global::asCurrentTexturePath = ( szTexturePath ); + Global.asCurrentTexturePath = ( szTexturePath ); } else if( filetype == ".t3d" ) { // z modelami jest prościej - Global::asCurrentTexturePath = Path; + Global.asCurrentTexturePath = Path; TModelsManager::GetModel( Path + filename, false ); } } @@ -2038,7 +2036,7 @@ void TWorld::CabChange(TDynamicObject *old, TDynamicObject *now) { // ewentualna zmiana kabiny użytkownikowi if (Train) if (Train->Dynamic() == old) - Global::changeDynObj = now; // uruchomienie protezy + Global.changeDynObj = now; // uruchomienie protezy }; void TWorld::ChangeDynamic() { @@ -2056,7 +2054,7 @@ void TWorld::ChangeDynamic() { Train->Dynamic()->MechInside = false; } } - TDynamicObject *temp = Global::changeDynObj; + TDynamicObject *temp = Global.changeDynObj; Train->Dynamic()->bDisplayCab = false; Train->Dynamic()->ABuSetModelShake( {} ); @@ -2070,7 +2068,7 @@ void TWorld::ChangeDynamic() { Train->DynamicSet( temp ); Controlled = temp; mvControlled = Controlled->ControlledFind()->MoverParameters; - Global::asHumanCtrlVehicle = Train->Dynamic()->name(); + Global.asHumanCtrlVehicle = Train->Dynamic()->name(); if( Train->Dynamic()->Mechanik ) // AI może sobie samo pójść if( !Train->Dynamic()->Mechanik->AIControllFlag ) // tylko jeśli ręcznie prowadzony { @@ -2088,15 +2086,15 @@ void TWorld::ChangeDynamic() { Train->MechStop(); FollowView(); // na pozycję mecha } - Global::changeDynObj = NULL; + Global.changeDynObj = NULL; } void TWorld::ToggleDaylight() { - Global::FakeLight = !Global::FakeLight; + Global.FakeLight = !Global.FakeLight; - if( Global::FakeLight ) { + if( Global.FakeLight ) { // for fake daylight enter fixed hour Environment.time( 10, 30, 0 ); } @@ -2125,7 +2123,7 @@ TWorld::compute_season( int const Yearday ) const { []( dayseasonpair const &Left, const int Right ) { return Left.first < Right; } ); - Global::Season = lookup->second + ":"; + Global.Season = lookup->second + ":"; } @@ -2154,9 +2152,9 @@ world_environment::update() { glm::vec3 keylightcolor; if( moonlightlevel > sunlightlevel ) { // rare situations when the moon is brighter than the sun, typically at night - Global::SunAngle = m_moon.getAngle(); - Global::DayLight.set_position( m_moon.getPosition() ); - Global::DayLight.direction = -1.0f * m_moon.getDirection(); + Global.SunAngle = m_moon.getAngle(); + Global.DayLight.position = m_moon.getPosition(); + Global.DayLight.direction = -1.0f * m_moon.getDirection(); keylightintensity = moonlightlevel; // if the moon is up, it overrides the twilight twilightfactor = 0.0f; @@ -2164,51 +2162,51 @@ world_environment::update() { } else { // regular situation with sun as the key light - Global::SunAngle = m_sun.getAngle(); - Global::DayLight.set_position( m_sun.getPosition() ); - Global::DayLight.direction = -1.0f * m_sun.getDirection(); + Global.SunAngle = m_sun.getAngle(); + Global.DayLight.position = m_sun.getPosition(); + Global.DayLight.direction = -1.0f * m_sun.getDirection(); keylightintensity = sunlightlevel; // include 'golden hour' effect in twilight lighting - float const duskfactor = 1.0f - clamp( Global::SunAngle, 0.0f, 18.0f ) / 18.0f; + float const duskfactor = 1.0f - clamp( Global.SunAngle, 0.0f, 18.0f ) / 18.0f; keylightcolor = interpolate( glm::vec3( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f ), glm::vec3( 235.0f / 255.0f, 140.0f / 255.0f, 36.0f / 255.0f ), duskfactor ); } // ...update skydome to match the current sun position as well... - m_skydome.SetOvercastFactor( Global::Overcast ); + m_skydome.SetOvercastFactor( Global.Overcast ); m_skydome.Update( m_sun.getDirection() ); // ...retrieve current sky colour and brightness... auto const skydomecolour = m_skydome.GetAverageColor(); - auto const skydomehsv = RGBtoHSV( skydomecolour ); + auto const skydomehsv = colors::RGBtoHSV( skydomecolour ); // sun strength is reduced by overcast level - keylightintensity *= ( 1.0f - std::min( 1.f, Global::Overcast ) * 0.65f ); + keylightintensity *= ( 1.0f - std::min( 1.f, Global.Overcast ) * 0.65f ); // intensity combines intensity of the sun and the light reflected by the sky dome // it'd be more technically correct to have just the intensity of the sun here, // but whether it'd _look_ better is something to be tested auto const intensity = std::min( 1.15f * ( 0.05f + keylightintensity + skydomehsv.z ), 1.25f ); // the impact of sun component is reduced proportionally to overcast level, as overcast increases role of ambient light - auto const diffuselevel = interpolate( keylightintensity, intensity * ( 1.0f - twilightfactor ), 1.0f - std::min( 1.f, Global::Overcast ) * 0.75f ); + auto const diffuselevel = interpolate( keylightintensity, intensity * ( 1.0f - twilightfactor ), 1.0f - std::min( 1.f, Global.Overcast ) * 0.75f ); // ...update light colours and intensity. keylightcolor = keylightcolor * diffuselevel; - Global::DayLight.diffuse = glm::vec4( keylightcolor, Global::DayLight.diffuse.a ); - Global::DayLight.specular = glm::vec4( keylightcolor * 0.85f, diffuselevel ); + Global.DayLight.diffuse = glm::vec4( keylightcolor, Global.DayLight.diffuse.a ); + Global.DayLight.specular = glm::vec4( keylightcolor * 0.85f, diffuselevel ); // tonal impact of skydome color is inversely proportional to how high the sun is above the horizon // (this is pure conjecture, aimed more to 'look right' than be accurate) - float const ambienttone = clamp( 1.0f - ( Global::SunAngle / 90.0f ), 0.0f, 1.0f ); - Global::DayLight.ambient[ 0 ] = interpolate( skydomehsv.z, skydomecolour.x, ambienttone ); - Global::DayLight.ambient[ 1 ] = interpolate( skydomehsv.z, skydomecolour.y, ambienttone ); - Global::DayLight.ambient[ 2 ] = interpolate( skydomehsv.z, skydomecolour.z, ambienttone ); + float const ambienttone = clamp( 1.0f - ( Global.SunAngle / 90.0f ), 0.0f, 1.0f ); + Global.DayLight.ambient[ 0 ] = interpolate( skydomehsv.z, skydomecolour.x, ambienttone ); + Global.DayLight.ambient[ 1 ] = interpolate( skydomehsv.z, skydomecolour.y, ambienttone ); + Global.DayLight.ambient[ 2 ] = interpolate( skydomehsv.z, skydomecolour.z, ambienttone ); - Global::fLuminance = intensity; + Global.fLuminance = intensity; // update the fog. setting it to match the average colour of the sky dome is cheap // but quite effective way to make the distant items blend with background better - Global::FogColor[ 0 ] = skydomecolour.x; - Global::FogColor[ 1 ] = skydomecolour.y; - Global::FogColor[ 2 ] = skydomecolour.z; + Global.FogColor[ 0 ] = skydomecolour.x; + Global.FogColor[ 1 ] = skydomecolour.y; + Global.FogColor[ 2 ] = skydomecolour.z; } void diff --git a/World.h b/World.h index 57bfa8ba..56736115 100644 --- a/World.h +++ b/World.h @@ -12,14 +12,13 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "classes.h" #include "Camera.h" -#include "scene.h" #include "sky.h" #include "sun.h" #include "moon.h" #include "stars.h" #include "skydome.h" -#include "mczapkie/mover.h" #include "messaging.h" // wrapper for simulation time diff --git a/audio.cpp b/audio.cpp index 63c36a5d..8d9da55b 100644 --- a/audio.cpp +++ b/audio.cpp @@ -11,8 +11,9 @@ http://mozilla.org/MPL/2.0/. #include "audio.h" #include "globals.h" -#include "mczapkie/mctools.h" +#include "utilities.h" #include "logs.h" +#include "resourcemanager.h" #define DR_WAV_IMPLEMENTATION #include "dr_wav.h" @@ -95,7 +96,7 @@ openal_buffer::fetch_caption() { std::string captionfilename { name }; captionfilename.erase( captionfilename.rfind( '.' ) ); // obcięcie rozszerzenia - captionfilename += "-" + Global::asLang + ".txt"; // już może być w różnych językach + captionfilename += "-" + Global.asLang + ".txt"; // już może być w różnych językach if( true == FileExists( captionfilename ) ) { // wczytanie std::ifstream inputfile( captionfilename ); @@ -133,13 +134,13 @@ buffer_manager::create( std::string const &Filename ) { audio::buffer_handle lookup { null_handle }; std::string filelookup; - if( false == Global::asCurrentDynamicPath.empty() ) { + if( false == Global.asCurrentDynamicPath.empty() ) { // try dynamic-specific sounds first - lookup = find_buffer( Global::asCurrentDynamicPath + filename ); + lookup = find_buffer( Global.asCurrentDynamicPath + filename ); if( lookup != null_handle ) { return lookup; } - filelookup = find_file( Global::asCurrentDynamicPath + filename ); + filelookup = find_file( Global.asCurrentDynamicPath + filename ); if( false == filelookup.empty() ) { return emplace( filelookup ); } diff --git a/audiorenderer.cpp b/audiorenderer.cpp index 2a7dcbdb..ae0cfed2 100644 --- a/audiorenderer.cpp +++ b/audiorenderer.cpp @@ -8,11 +8,13 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" - #include "audiorenderer.h" + #include "sound.h" #include "globals.h" +#include "camera.h" #include "logs.h" +#include "utilities.h" namespace audio { @@ -94,7 +96,7 @@ openal_source::sync_with( sound_properties const &State ) { */ // location properties.location = State.location; - sound_distance = properties.location - glm::dvec3 { Global::pCameraPosition }; + sound_distance = properties.location - glm::dvec3 { Global.pCameraPosition }; if( sound_range > 0 ) { // range cutoff check auto const cutoffrange = ( @@ -122,7 +124,7 @@ openal_source::sync_with( sound_properties const &State ) { properties.soundproofing = State.soundproofing; properties.soundproofing_stamp = State.soundproofing_stamp; - ::alSourcef( id, AL_GAIN, properties.gain * properties.soundproofing * Global::AudioVolume ); + ::alSourcef( id, AL_GAIN, properties.gain * properties.soundproofing * Global.AudioVolume ); } if( sound_range > 0 ) { auto const rangesquared { sound_range * sound_range }; @@ -138,7 +140,7 @@ openal_source::sync_with( sound_properties const &State ) { clamp( ( distancesquared - rangesquared ) / ( fadedistance * fadedistance ), 0.f, 1.f ) ) }; - ::alSourcef( id, AL_GAIN, properties.gain * properties.soundproofing * rangefactor * Global::AudioVolume ); + ::alSourcef( id, AL_GAIN, properties.gain * properties.soundproofing * rangefactor * Global.AudioVolume ); } is_in_range = ( distancesquared <= rangesquared ); } @@ -254,7 +256,7 @@ openal_renderer::init() { // // ::alDistanceModel( AL_LINEAR_DISTANCE ); ::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED ); - ::alListenerf( AL_GAIN, clamp( Global::AudioVolume, 1.f, 4.f ) ); + ::alListenerf( AL_GAIN, clamp( Global.AudioVolume, 1.f, 4.f ) ); // all done m_ready = true; return true; @@ -288,14 +290,14 @@ openal_renderer::update( double const Deltatime ) { // update listener glm::dmat4 cameramatrix; - Global::pCamera->SetMatrix( cameramatrix ); + Global.pCamera->SetMatrix( cameramatrix ); auto rotationmatrix { glm::mat3{ cameramatrix } }; glm::vec3 const orientation[] = { glm::vec3{ 0, 0,-1 } * rotationmatrix , glm::vec3{ 0, 1, 0 } * rotationmatrix }; ::alListenerfv( AL_ORIENTATION, reinterpret_cast( orientation ) ); /* - glm::dvec3 const listenerposition { Global::pCameraPosition }; + glm::dvec3 const listenerposition { Global.pCameraPosition }; // not used yet glm::vec3 const velocity { ( listenerposition - m_listenerposition ) / Deltatime }; m_listenerposition = listenerposition; @@ -380,7 +382,7 @@ bool openal_renderer::init_caps() { // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = ::alcOpenDevice( Global::AudioRenderer.c_str() ); + m_device = ::alcOpenDevice( Global.AudioRenderer.c_str() ); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; diff --git a/audiorenderer.h b/audiorenderer.h index e20608f2..e0cc5cd9 100644 --- a/audiorenderer.h +++ b/audiorenderer.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "audio.h" #include "resourcemanager.h" +#include "uitranscripts.h" class sound_source; @@ -166,7 +167,7 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ auto const &buffer { audio::renderer.buffer( bufferhandle ) }; buffers.emplace_back( buffer.id ); if( false == buffer.caption.empty() ) { - Global::tranTexts.Add( buffer.caption ); } } ); + ui::Transcripts.Add( buffer.caption ); } } ); if( id != audio::null_resource ) { ::alSourceQueueBuffers( id, static_cast( buffers.size() ), buffers.data() ); diff --git a/color.h b/color.h index 0a618426..af6408a0 100644 --- a/color.h +++ b/color.h @@ -1,6 +1,9 @@ #pragma once -#include "float3d.h" +namespace colors { + +glm::vec4 const none{ 0.f, 0.f, 0.f, 1.f }; +glm::vec4 const white{ 1.f, 1.f, 1.f, 1.f }; inline glm::vec3 @@ -116,3 +119,5 @@ HSVtoRGB( glm::vec3 const &HSV ) { } return rgb; } + +} // namespace colors diff --git a/command.cpp b/command.cpp index 6a2f72ff..b24c988c 100644 --- a/command.cpp +++ b/command.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "globals.h" #include "logs.h" #include "timer.h" +#include "utilities.h" namespace simulation { @@ -178,7 +179,7 @@ command_relay::post( user_command const Command, std::uint64_t const Param1, std if( ( command.target == command_target::vehicle ) && ( true == FreeFlyModeFlag ) && ( ( false == DebugModeFlag ) - && ( true == Global::RealisticControlMode ) ) ) { + && ( true == Global.RealisticControlMode ) ) ) { // in realistic control mode don't pass vehicle commands if the user isn't in one, unless we're in debug mode return; } diff --git a/gamepadinput.cpp b/gamepadinput.cpp index 91f0cacf..ec433f1c 100644 --- a/gamepadinput.cpp +++ b/gamepadinput.cpp @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "gamepadinput.h" #include "logs.h" #include "timer.h" -#include "usefull.h" +#include "utilities.h" glm::vec2 circle_to_square( glm::vec2 const &Point, int const Roundness = 0 ) { diff --git a/keyboardinput.cpp b/keyboardinput.cpp index 2fde9b6d..c619436c 100644 --- a/keyboardinput.cpp +++ b/keyboardinput.cpp @@ -460,12 +460,12 @@ keyboard_input::poll() { glm::vec2 const movementhorizontal { // x-axis - ( Global::shiftState ? 1.f : 0.5f ) * + ( Global.shiftState ? 1.f : 0.5f ) * ( m_keys[ m_bindingscache.left ] != GLFW_RELEASE ? -1.f : m_keys[ m_bindingscache.right ] != GLFW_RELEASE ? 1.f : 0.f ), // z-axis - ( Global::shiftState ? 1.f : 0.5f ) * + ( Global.shiftState ? 1.f : 0.5f ) * ( m_keys[ m_bindingscache.forward ] != GLFW_RELEASE ? 1.f : m_keys[ m_bindingscache.back ] != GLFW_RELEASE ? -1.f : 0.f ) }; @@ -475,7 +475,7 @@ keyboard_input::poll() { double const movexparam = static_cast( movementhorizontal.x ); double const movezparam = static_cast( movementhorizontal.y ); m_relay.post( - ( true == Global::ctrlState ? + ( true == Global.ctrlState ? user_command::movehorizontalfast : user_command::movehorizontal ), reinterpret_cast( movexparam ), @@ -488,7 +488,7 @@ keyboard_input::poll() { float const movementvertical { // y-axis - ( Global::shiftState ? 1.f : 0.5f ) * + ( Global.shiftState ? 1.f : 0.5f ) * ( m_keys[ m_bindingscache.up ] != GLFW_RELEASE ? 1.f : m_keys[ m_bindingscache.down ] != GLFW_RELEASE ? -1.f : 0.f ) }; @@ -497,7 +497,7 @@ keyboard_input::poll() { || ( m_movementvertical != 0.f ) ) { double const moveyparam = static_cast( movementvertical ); m_relay.post( - ( true == Global::ctrlState ? + ( true == Global.ctrlState ? user_command::moveverticalfast : user_command::movevertical ), reinterpret_cast( moveyparam ), diff --git a/light.cpp b/light.cpp new file mode 100644 index 00000000..c17195c7 --- /dev/null +++ b/light.cpp @@ -0,0 +1,11 @@ +/* +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 "light.h" diff --git a/light.h b/light.h new file mode 100644 index 00000000..3eac437d --- /dev/null +++ b/light.h @@ -0,0 +1,23 @@ +/* +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/. +*/ + +#pragma once + +#include "color.h" + +// a simple light source, either omni- or directional +struct basic_light { + + glm::vec4 ambient { colors::none }; + glm::vec4 diffuse { colors::white }; + glm::vec4 specular { colors::white }; + glm::vec3 position; + glm::vec3 direction; + bool is_omnidirectional { true }; +}; diff --git a/lightarray.cpp b/lightarray.cpp index 9655da56..1c82284b 100644 --- a/lightarray.cpp +++ b/lightarray.cpp @@ -15,8 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "lightarray.h" + #include "dynobj.h" -#include "driver.h" void light_array::insert( TDynamicObject const *Owner ) { diff --git a/lightarray.h b/lightarray.h index ff7b694e..700a34cd 100644 --- a/lightarray.h +++ b/lightarray.h @@ -1,9 +1,6 @@ #pragma once -#include -#include "dumb3d.h" -#include "float3d.h" -#include "dynobj.h" +#include "classes.h" // collection of virtual light sources present in the scene // used by the renderer to determine most suitable placement for actual light sources during render diff --git a/maszyna.vcxproj.filters b/maszyna.vcxproj.filters index 5ac1908c..b02c522c 100644 --- a/maszyna.vcxproj.filters +++ b/maszyna.vcxproj.filters @@ -135,9 +135,6 @@ Source Files\input - - Source Files\mczapkie - Source Files\mczapkie @@ -234,6 +231,12 @@ Source Files + + Source Files + + + Source Files + @@ -257,9 +260,6 @@ Header Files - - Header Files - Header Files @@ -296,9 +296,6 @@ Header Files\mczapkie - - Header Files\mczapkie - Header Files\mczapkie @@ -455,6 +452,15 @@ Header Files + + Header Files + + + Header Files + + + Header Files + diff --git a/material.cpp b/material.cpp index 7e49e030..470d5ea4 100644 --- a/material.cpp +++ b/material.cpp @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "material.h" #include "renderer.h" -#include "usefull.h" +#include "utilities.h" #include "globals.h" bool @@ -51,13 +51,13 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c if( value == "{" ) { // detect and optionally process config blocks cParser blockparser( Input.getToken( false, "}" ) ); - if( key == Global::Season ) { + if( key == Global.Season ) { // seasonal textures override generic textures while( true == deserialize_mapping( blockparser, 1, Loadnow ) ) { ; // all work is done in the header } } - else if( key == Global::Weather ) { + else if( key == Global.Weather ) { // weather textures override generic and seasonal textures while( true == deserialize_mapping( blockparser, 2, Loadnow ) ) { ; // all work is done in the header diff --git a/material.h b/material.h index 881c14b9..36341a23 100644 --- a/material.h +++ b/material.h @@ -9,8 +9,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include "classes.h" #include "texture.h" -#include "parser.h" typedef int material_handle; diff --git a/messaging.cpp b/messaging.cpp index feb674dc..c9e59ded 100644 --- a/messaging.cpp +++ b/messaging.cpp @@ -47,7 +47,7 @@ WyslijEvent(const std::string &e, const std::string &d) cData.dwData = MAKE_ID4( 'E', 'U', '0', '7' ); // sygnatura cData.cbData = (DWORD)(12 + i + j); // 8+dwa liczniki i dwa zera kończące cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); CommLog( Now() + " " + std::to_string(r.iComm) + " " + e + " sent" ); } @@ -65,7 +65,7 @@ WyslijUszkodzenia(const std::string &t, char fl) cData.dwData = MAKE_ID4( 'E', 'U', '0', '7' ); // sygnatura cData.cbData = (DWORD)(11 + i); // 8+licznik i zero kończące cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); } @@ -82,7 +82,7 @@ WyslijString(const std::string &t, int n) cData.dwData = MAKE_ID4( 'E', 'U', '0', '7' ); // sygnatura cData.cbData = (DWORD)(10 + i); // 8+licznik i zero kończące cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); } @@ -102,7 +102,7 @@ WyslijNamiary(TDynamicObject const *Vehicle) int i = 32; size_t j = Vehicle->asName.length(); r.iPar[0] = i; // ilość danych liczbowych - r.fPar[1] = Global::fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) + r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) r.fPar[2] = Vehicle->MoverParameters->Loc.X; // pozycja X r.fPar[3] = Vehicle->MoverParameters->Loc.Y; // pozycja Y r.fPar[4] = Vehicle->MoverParameters->Loc.Z; // pozycja Z @@ -164,7 +164,7 @@ WyslijNamiary(TDynamicObject const *Vehicle) cData.cbData = (DWORD)(10 + i + j); // 8+licznik i zero kończące cData.lpData = &r; // WriteLog("Ramka gotowa"); - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); // WriteLog("Ramka poszla!"); CommLog( Now() + " " + std::to_string(r.iComm) + " " + Vehicle->asName + " sent"); } @@ -211,7 +211,7 @@ WyslijObsadzone() cData.cbData = 8 + 1984; // 8+licznik i zero kończące cData.lpData = &r; // WriteLog("Ramka gotowa"); - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); CommLog( Now() + " " + std::to_string(r.iComm) + " obsadzone" + " sent"); } @@ -226,8 +226,8 @@ WyslijParam(int nr, int fl) switch (nr) { // można tym przesyłać różne zestawy parametrów case 5: // czas i pauza - r.fPar[1] = Global::fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) - r.iPar[2] = Global::iPause; // stan zapauzowania + r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) + r.iPar[2] = Global.iPause; // stan zapauzowania i = 8; // dwa parametry po 4 bajty każdy break; } @@ -235,7 +235,7 @@ WyslijParam(int nr, int fl) cData.dwData = MAKE_ID4( 'E', 'U', '0', '7' ); // sygnatura cData.cbData = 12 + i; // 12+rozmiar danych cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData ); + Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global.window ), (LPARAM)&cData ); } #endif diff --git a/moon.cpp b/moon.cpp index d4da4c38..9722140f 100644 --- a/moon.cpp +++ b/moon.cpp @@ -3,7 +3,7 @@ #include "moon.h" #include "globals.h" #include "mtable.h" -#include "usefull.h" +#include "utilities.h" #include "world.h" ////////////////////////////////////////////////////////////////////////////////////////// @@ -36,7 +36,7 @@ void cMoon::update() { move(); - glm::vec3 position( 0.f, 0.f, -2000.f * Global::fDistanceFactor ); + glm::vec3 position( 0.f, 0.f, -2000.f * Global.fDistanceFactor ); position = glm::rotateX( position, glm::radians( static_cast( m_body.elevref ) ) ); position = glm::rotateY( position, glm::radians( static_cast( -m_body.hrang ) ) ); @@ -54,7 +54,7 @@ cMoon::render() { ::glEnd(); ::glPushMatrix(); ::glTranslatef( m_position.x, m_position.y, m_position.z ); - ::gluSphere( moonsphere, /* (float)( Global::iWindowHeight / Global::FieldOfView ) * 0.5 * */ ( m_body.distance / 60.2666 ) * 9.037461, 12, 12 ); + ::gluSphere( moonsphere, /* (float)( Global.iWindowHeight / Global.FieldOfView ) * 0.5 * */ ( m_body.distance / 60.2666 ) * 9.037461, 12, 12 ); ::glPopMatrix(); } diff --git a/mouseinput.cpp b/mouseinput.cpp index f885e090..873d8b90 100644 --- a/mouseinput.cpp +++ b/mouseinput.cpp @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "mouseinput.h" -#include "usefull.h" +#include "utilities.h" #include "globals.h" #include "timer.h" #include "world.h" @@ -36,7 +36,7 @@ mouse_input::init() { void mouse_input::move( double Mousex, double Mousey ) { - if( false == Global::ControlPicking ) { + if( false == Global.ControlPicking ) { // default control mode m_relay.post( user_command::viewturn, @@ -71,7 +71,7 @@ mouse_input::move( double Mousex, double Mousey ) { void mouse_input::button( int const Button, int const Action ) { - if( false == Global::ControlPicking ) { return; } + if( false == Global.ControlPicking ) { return; } if( true == FreeFlyModeFlag ) { // world editor controls @@ -128,7 +128,7 @@ mouse_input::button( int const Button, int const Action ) { ); if( mousecommand != user_command::none ) { // check manually for commands which have 'fast' variants launched with shift modifier - if( Global::shiftState ) { + if( Global.shiftState ) { switch( mousecommand ) { case user_command::mastercontrollerincrease: { mousecommand = user_command::mastercontrollerincreasefast; break; } case user_command::mastercontrollerdecrease: { mousecommand = user_command::mastercontrollerdecreasefast; break; } @@ -184,7 +184,7 @@ mouse_input::poll() { auto updaterate { m_updaterate }; if( m_varyingpollrate ) { - updaterate /= std::max( 0.15, 2.0 * glm::length( m_cursorposition - m_commandstartcursor ) / std::max( 1, Global::iWindowHeight ) ); + updaterate /= std::max( 0.15, 2.0 * glm::length( m_cursorposition - m_commandstartcursor ) / std::max( 1, Global.iWindowHeight ) ); } while( m_updateaccumulator > updaterate ) { diff --git a/mtable.cpp b/mtable.cpp index 34faea9f..3cc1b0fd 100644 --- a/mtable.cpp +++ b/mtable.cpp @@ -9,7 +9,9 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "mtable.h" -#include "mczapkie/mctools.h" + +#include "world.h" +#include "utilities.h" double CompareTime(double t1h, double t1m, double t2h, double t2m) /*roznica czasu w minutach*/ // zwraca różnicę czasu diff --git a/mtable.h b/mtable.h index f5471f81..a456cffc 100644 --- a/mtable.h +++ b/mtable.h @@ -10,7 +10,8 @@ http://mozilla.org/MPL/2.0/. #pragma once #include -#include "world.h" + +#include "classes.h" namespace Mtable { diff --git a/McZapkie/mctools.cpp b/old/mctools.cpp similarity index 89% rename from McZapkie/mctools.cpp rename to old/mctools.cpp index 4fff8667..e653d75a 100644 --- a/McZapkie/mctools.cpp +++ b/old/mctools.cpp @@ -89,7 +89,7 @@ bool ClearFlag( int &Flag, int const Value ) { inline double Random(double a, double b) { std::uniform_real_distribution<> dis(a, b); - return dis(Global::random_engine); + return dis(Global.random_engine); } bool FuzzyLogic(double Test, double Threshold, double Probability) @@ -267,6 +267,25 @@ win1250_to_ascii( std::string &Input ) { } } +// Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów +char bezogonkowo[] = "E?,?\"_++?%Sstzz" + " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" + "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" + "raaaalccceeeeiiddnnoooo-ruuuuyt?"; + +std::string Bezogonkow(std::string str, bool _) +{ // wycięcie liter z ogonkami, bo OpenGL nie umie wyświetlić + for (unsigned int i = 1; i < str.length(); ++i) + if (str[i] & 0x80) + str[i] = bezogonkowo[str[i] & 0x7F]; + else if (str[i] < ' ') // znaki sterujące nie są obsługiwane + str[i] = ' '; + else if (_) + if (str[i] == '_') // nazwy stacji nie mogą zawierać spacji + str[i] = ' '; // więc trzeba wyświetlać inaczej + return str; +}; + template <> bool extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) { diff --git a/McZapkie/mctools.h b/old/mctools.h similarity index 98% rename from McZapkie/mctools.h rename to old/mctools.h index 88bdc80f..819791e2 100644 --- a/McZapkie/mctools.h +++ b/old/mctools.h @@ -112,6 +112,8 @@ std::string ToUpper(std::string const &text); // replaces polish letters with basic ascii void win1250_to_ascii( std::string &Input ); +// TODO: unify with win1250_to_ascii() +std::string Bezogonkow( std::string str, bool _ = false ); inline std::string diff --git a/openglgeometrybank.cpp b/openglgeometrybank.cpp index dc8989a3..02fde9db 100644 --- a/openglgeometrybank.cpp +++ b/openglgeometrybank.cpp @@ -392,7 +392,7 @@ geometrybank_manager::update() { gfx::geometrybank_handle geometrybank_manager::create_bank() { - if( true == Global::bUseVBO ) { m_geometrybanks.emplace_back( std::make_shared(), std::chrono::steady_clock::time_point() ); } + if( true == Global.bUseVBO ) { m_geometrybanks.emplace_back( std::make_shared(), std::chrono::steady_clock::time_point() ); } else { m_geometrybanks.emplace_back( std::make_shared(), std::chrono::steady_clock::time_point() ); } // NOTE: handle is effectively (index into chunk array + 1) this leaves value of 0 to serve as error/empty handle indication return { static_cast( m_geometrybanks.size() ), 0 }; diff --git a/renderer.cpp b/renderer.cpp index 2177046d..1d72f481 100644 --- a/renderer.cpp +++ b/renderer.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "renderer.h" +#include "color.h" #include "globals.h" #include "timer.h" #include "simulation.h" @@ -20,7 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "traction.h" #include "uilayer.h" #include "logs.h" -#include "usefull.h" +#include "utilities.h" opengl_renderer GfxRenderer; extern TWorld World; @@ -28,12 +29,33 @@ extern TWorld World; int const EU07_PICKBUFFERSIZE { 1024 }; // size of (square) textures bound with the pick framebuffer int const EU07_ENVIRONMENTBUFFERSIZE { 256 }; // size of (square) environmental cube map texture -namespace colors { +void +opengl_light::apply_intensity( float const Factor ) { -glm::vec4 const none { 0.f, 0.f, 0.f, 1.f }; -glm::vec4 const white{ 1.f, 1.f, 1.f, 1.f }; + if( Factor == 1.0 ) { + + ::glLightfv( id, GL_AMBIENT, glm::value_ptr( ambient ) ); + ::glLightfv( id, GL_DIFFUSE, glm::value_ptr( diffuse ) ); + ::glLightfv( id, GL_SPECULAR, glm::value_ptr( specular ) ); + } + else { + // temporary light scaling mechanics (ultimately this work will be left to the shaders + glm::vec4 scaledambient( ambient.r * Factor, ambient.g * Factor, ambient.b * Factor, ambient.a ); + glm::vec4 scaleddiffuse( diffuse.r * Factor, diffuse.g * Factor, diffuse.b * Factor, diffuse.a ); + glm::vec4 scaledspecular( specular.r * Factor, specular.g * Factor, specular.b * Factor, specular.a ); + glLightfv( id, GL_AMBIENT, glm::value_ptr( scaledambient ) ); + glLightfv( id, GL_DIFFUSE, glm::value_ptr( scaleddiffuse ) ); + glLightfv( id, GL_SPECULAR, glm::value_ptr( scaledspecular ) ); + } +} + +void +opengl_light::apply_angle() { + + ::glLightfv( id, GL_POSITION, glm::value_ptr( position ) ); + ::glLightfv( id, GL_SPOT_DIRECTION, glm::value_ptr( glm::vec4{ direction, ( is_omnidirectional ? 1.f : 0.f ) } ) ); +} -} // namespace colors void opengl_camera::update_frustum( glm::mat4 const &Projection, glm::mat4 const &Modelview ) { @@ -100,7 +122,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { glShadeModel( GL_SMOOTH ); // Enable Smooth Shading m_geometry.units().texture = ( - Global::BasicRenderer ? + Global.BasicRenderer ? std::vector{ m_diffusetextureunit } : std::vector{ m_normaltextureunit, m_diffusetextureunit } ); m_textures.assign_units( m_helpertextureunit, m_shadowtextureunit, m_normaltextureunit, m_diffusetextureunit ); // TODO: add reflections unit @@ -124,7 +146,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { ::glLightModeli( GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR ); ::glMaterialf( GL_FRONT, GL_SHININESS, 15.0f ); - if( true == Global::ScaleSpecularValues ) { + if( true == Global.ScaleSpecularValues ) { m_specularopaquescalefactor = 0.25f; m_speculartranslucentscalefactor = 1.5f; } @@ -136,23 +158,21 @@ opengl_renderer::Init( GLFWwindow *Window ) { ::glEnable( GL_LIGHTING ); ::glEnable( GL_LIGHT0 ); - Global::DayLight.id = opengl_renderer::sunlight; - // directional light - // TODO, TBD: test omni-directional variant - Global::DayLight.position[ 3 ] = 1.0f; - ::glLightf( opengl_renderer::sunlight, GL_SPOT_CUTOFF, 90.0f ); + m_sunlight.id = opengl_renderer::sunlight; +// ::glLightf( opengl_renderer::sunlight, GL_SPOT_CUTOFF, 90.0f ); + Global.DayLight.is_omnidirectional = true; // rgb value for 5780 kelvin - Global::DayLight.diffuse[ 0 ] = 255.0f / 255.0f; - Global::DayLight.diffuse[ 1 ] = 242.0f / 255.0f; - Global::DayLight.diffuse[ 2 ] = 231.0f / 255.0f; + Global.DayLight.diffuse[ 0 ] = 255.0f / 255.0f; + Global.DayLight.diffuse[ 1 ] = 242.0f / 255.0f; + Global.DayLight.diffuse[ 2 ] = 231.0f / 255.0f; // create dynamic light pool - for( int idx = 0; idx < Global::DynamicLightCount; ++idx ) { + for( int idx = 0; idx < Global.DynamicLightCount; ++idx ) { opengl_light light; light.id = GL_LIGHT1 + idx; - light.position[ 3 ] = 1.0f; + light.is_omnidirectional = true; ::glLightf( light.id, GL_SPOT_CUTOFF, 7.5f ); ::glLightf( light.id, GL_SPOT_EXPONENT, 7.5f ); ::glLightf( light.id, GL_CONSTANT_ATTENUATION, 0.0f ); @@ -204,7 +224,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { } #endif // shadowmap resources - if( ( true == Global::RenderShadows ) + if( ( true == Global.RenderShadows ) && ( true == m_framebuffersupport ) ) { // primary shadow map { @@ -252,7 +272,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { } else { ErrorLog( "Shadows framebuffer setup failed" ); - Global::RenderShadows = false; + Global.RenderShadows = false; } // switch back to primary render target for now ::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); @@ -305,14 +325,14 @@ opengl_renderer::Init( GLFWwindow *Window ) { } else { ErrorLog( "Cab shadows framebuffer setup failed" ); - Global::RenderShadows = false; + Global.RenderShadows = false; } } // switch back to primary render target for now ::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); } // environment cube map resources - if( ( false == Global::BasicRenderer ) + if( ( false == Global.BasicRenderer ) && ( true == m_framebuffersupport ) ) { // texture: ::glGenTextures( 1, &m_environmentcubetexture ); @@ -417,8 +437,8 @@ opengl_renderer::Render_pass( rendermode const Mode ) { case rendermode::color: { - if( ( true == Global::RenderShadows ) - && ( false == Global::bWireFrame ) + if( ( true == Global.RenderShadows ) + && ( false == Global.bWireFrame ) && ( true == World.InitPerformed() ) && ( m_shadowcolor != colors::white ) ) { @@ -465,7 +485,7 @@ opengl_renderer::Render_pass( rendermode const Mode ) { } } - ::glViewport( 0, 0, Global::iWindowWidth, Global::iWindowHeight ); + ::glViewport( 0, 0, Global.iWindowWidth, Global.iWindowHeight ); if( World.InitPerformed() ) { auto const skydomecolour = World.Environment.m_skydome.GetAverageColor(); @@ -493,7 +513,7 @@ opengl_renderer::Render_pass( rendermode const Mode ) { ::glColor4f( 1.f, 0.9f, 0.8f, 1.f ); ::glDisable( GL_LIGHTING ); ::glDisable( GL_TEXTURE_2D ); - if( ( true == Global::RenderShadows ) && ( false == Global::bWireFrame ) ) { + if( ( true == Global.RenderShadows ) && ( false == Global.bWireFrame ) ) { m_shadowpass.camera.draw( m_renderpass.camera.position() - m_shadowpass.camera.position() ); } if( DebugCameraFlag ) { @@ -758,12 +778,12 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f if( false == World.InitPerformed() ) { return; } // setup draw range switch( Mode ) { - case rendermode::color: { Config.draw_range = Global::BaseDrawRange; break; } - case rendermode::shadows: { Config.draw_range = Global::BaseDrawRange * 0.5f; break; } - case rendermode::cabshadows: { Config.draw_range = ( Global::pWorld->train()->Dynamic()->MoverParameters->ActiveCab != 0 ? 10.f : 20.f ); break; } - case rendermode::reflections: { Config.draw_range = Global::BaseDrawRange; break; } + case rendermode::color: { Config.draw_range = Global.BaseDrawRange; break; } + case rendermode::shadows: { Config.draw_range = Global.BaseDrawRange * 0.5f; break; } + case rendermode::cabshadows: { Config.draw_range = ( Global.pWorld->train()->Dynamic()->MoverParameters->ActiveCab != 0 ? 10.f : 20.f ); break; } + case rendermode::reflections: { Config.draw_range = Global.BaseDrawRange; break; } case rendermode::pickcontrols: { Config.draw_range = 50.f; break; } - case rendermode::pickscenery: { Config.draw_range = Global::BaseDrawRange * 0.5f; break; } + case rendermode::pickscenery: { Config.draw_range = Global.BaseDrawRange * 0.5f; break; } default: { Config.draw_range = 0.f; break; } } // setup camera @@ -776,23 +796,23 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f case rendermode::color: { // modelview if( ( false == DebugCameraFlag ) || ( true == Ignoredebug ) ) { - camera.position() = Global::pCameraPosition; + camera.position() = Global.pCameraPosition; World.Camera.SetMatrix( viewmatrix ); } else { - camera.position() = Global::DebugCameraPosition; + camera.position() = Global.DebugCameraPosition; World.DebugCamera.SetMatrix( viewmatrix ); } // projection - auto const zfar = Config.draw_range * Global::fDistanceFactor * Zfar; + auto const zfar = Config.draw_range * Global.fDistanceFactor * Zfar; auto const znear = ( Znear > 0.f ? Znear * zfar : - 0.1f * Global::ZoomFactor ); + 0.1f * Global.ZoomFactor ); camera.projection() *= glm::perspective( - glm::radians( Global::FieldOfView / Global::ZoomFactor ), - std::max( 1.f, (float)Global::iWindowWidth ) / std::max( 1.f, (float)Global::iWindowHeight ), + glm::radians( Global.FieldOfView / Global.ZoomFactor ), + std::max( 1.f, (float)Global.iWindowWidth ) / std::max( 1.f, (float)Global.iWindowHeight ), znear, zfar ); break; @@ -800,7 +820,7 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f case rendermode::shadows: { // calculate lightview boundaries based on relevant area of the world camera frustum: // ...setup chunk of frustum we're interested in... - auto const zfar = std::min( 1.f, Global::shadowtune.depth / ( Global::BaseDrawRange * Global::fDistanceFactor ) * std::max( 1.f, Global::ZoomFactor * 0.5f ) ); + auto const zfar = std::min( 1.f, Global.shadowtune.depth / ( Global.BaseDrawRange * Global.fDistanceFactor ) * std::max( 1.f, Global.ZoomFactor * 0.5f ) ); renderpass_config worldview; setup_pass( worldview, rendermode::color, 0.f, zfar, true ); auto &frustumchunkshapepoints = worldview.camera.frustum_points(); @@ -811,9 +831,9 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f // ...cap the vertical angle to keep shadows from getting too long... auto const lightvector = glm::normalize( glm::vec3{ - Global::DayLight.direction.x, - std::min( Global::DayLight.direction.y, -0.2f ), - Global::DayLight.direction.z } ); + Global.DayLight.direction.x, + std::min( Global.DayLight.direction.y, -0.2f ), + Global.DayLight.direction.z } ); // ...place the light source at the calculated centre and setup world space light view matrix... camera.position() = worldview.camera.position() + glm::dvec3{ frustumchunkcentre }; viewmatrix *= glm::lookAt( @@ -830,7 +850,7 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f } bounding_box( frustumchunkmin, frustumchunkmax, std::begin( frustumchunkshapepoints ), std::end( frustumchunkshapepoints ) ); // quantize the frustum points and add some padding, to reduce shadow shimmer on scale changes - auto const quantizationstep{ std::min( Global::shadowtune.depth, 50.f ) }; + auto const quantizationstep{ std::min( Global.shadowtune.depth, 50.f ) }; frustumchunkmin = quantizationstep * glm::floor( frustumchunkmin * ( 1.f / quantizationstep ) ); frustumchunkmax = quantizationstep * glm::ceil( frustumchunkmax * ( 1.f / quantizationstep ) ); // ...use the dimensions to set up light projection boundaries... @@ -844,16 +864,16 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f // fixed ortho projection from old build, for quick quality comparisons camera.projection() *= glm::ortho( - -Global::shadowtune.width, Global::shadowtune.width, - -Global::shadowtune.width, Global::shadowtune.width, - -Global::shadowtune.depth, Global::shadowtune.depth ); - camera.position() = Global::pCameraPosition - glm::dvec3{ Global::DayLight.direction }; - if( camera.position().y - Global::pCameraPosition.y < 0.1 ) { - camera.position().y = Global::pCameraPosition.y + 0.1; + -Global.shadowtune.width, Global.shadowtune.width, + -Global.shadowtune.width, Global.shadowtune.width, + -Global.shadowtune.depth, Global.shadowtune.depth ); + camera.position() = Global.pCameraPosition - glm::dvec3{ Global.DayLight.direction }; + if( camera.position().y - Global.pCameraPosition.y < 0.1 ) { + camera.position().y = Global.pCameraPosition.y + 0.1; } viewmatrix *= glm::lookAt( camera.position(), - glm::dvec3{ Global::pCameraPosition }, + glm::dvec3{ Global.pCameraPosition }, glm::dvec3{ 0.f, 1.f, 0.f } ); */ // ... and adjust the projection to sample complete shadow map texels: @@ -874,13 +894,13 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f // modelview auto const lightvector = glm::normalize( glm::vec3{ - Global::DayLight.direction.x, - std::min( Global::DayLight.direction.y, -0.2f ), - Global::DayLight.direction.z } ); - camera.position() = Global::pCameraPosition - glm::dvec3 { lightvector }; + Global.DayLight.direction.x, + std::min( Global.DayLight.direction.y, -0.2f ), + Global.DayLight.direction.z } ); + camera.position() = Global.pCameraPosition - glm::dvec3 { lightvector }; viewmatrix *= glm::lookAt( camera.position(), - glm::dvec3 { Global::pCameraPosition }, + glm::dvec3 { Global.pCameraPosition }, glm::dvec3 { 0.f, 1.f, 0.f } ); // projection auto const maphalfsize { Config.draw_range * 0.5f }; @@ -902,8 +922,8 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f // modelview camera.position() = ( ( ( true == DebugCameraFlag ) && ( false == Ignoredebug ) ) ? - Global::DebugCameraPosition : - Global::pCameraPosition ); + Global.DebugCameraPosition : + Global.pCameraPosition ); glm::dvec3 const cubefacetargetvectors[ 6 ] = { { 1.0, 0.0, 0.0 }, { -1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, -1.0 } }; glm::dvec3 const cubefaceupvectors[ 6 ] = { { 0.0, -1.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, -1.0 }, { 0.0, -1.0, 0.0 }, { 0.0, -1.0, 0.0 } }; auto const cubefaceindex = m_environmentcubetextureface - GL_TEXTURE_CUBE_MAP_POSITIVE_X; @@ -917,8 +937,8 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f glm::perspective( glm::radians( 90.f ), 1.f, - 0.1f * Global::ZoomFactor, - Config.draw_range * Global::fDistanceFactor ); + 0.1f * Global.ZoomFactor, + Config.draw_range * Global.fDistanceFactor ); break; } @@ -926,15 +946,15 @@ opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, f case rendermode::pickscenery: { // TODO: scissor test for pick modes // modelview - camera.position() = Global::pCameraPosition; + camera.position() = Global.pCameraPosition; World.Camera.SetMatrix( viewmatrix ); // projection camera.projection() *= glm::perspective( - glm::radians( Global::FieldOfView / Global::ZoomFactor ), - std::max( 1.f, (float)Global::iWindowWidth ) / std::max( 1.f, (float)Global::iWindowHeight ), - 0.1f * Global::ZoomFactor, - Config.draw_range * Global::fDistanceFactor ); + glm::radians( Global.FieldOfView / Global.ZoomFactor ), + std::max( 1.f, (float)Global.iWindowWidth ) / std::max( 1.f, (float)Global.iWindowHeight ), + 0.1f * Global.ZoomFactor, + Config.draw_range * Global.fDistanceFactor ); break; } default: { @@ -984,14 +1004,14 @@ opengl_renderer::setup_drawing( bool const Alpha ) { case rendermode::reflections: { ::glEnable( GL_LIGHTING ); ::glShadeModel( GL_SMOOTH ); - if( Global::iMultisampling ) { + if( Global.iMultisampling ) { ::glEnable( GL_MULTISAMPLE ); } // setup fog - if( Global::fFogEnd > 0 ) { + if( Global.fFogEnd > 0 ) { // fog setup - ::glFogfv( GL_FOG_COLOR, Global::FogColor ); - ::glFogf( GL_FOG_DENSITY, static_cast( 1.0 / Global::fFogEnd ) ); + ::glFogfv( GL_FOG_COLOR, Global.FogColor ); + ::glFogf( GL_FOG_DENSITY, static_cast( 1.0 / Global.fFogEnd ) ); ::glEnable( GL_FOG ); } else { ::glDisable( GL_FOG ); } @@ -1005,7 +1025,7 @@ opengl_renderer::setup_drawing( bool const Alpha ) { ::glColor4fv( glm::value_ptr( colors::white ) ); ::glDisable( GL_LIGHTING ); ::glShadeModel( GL_FLAT ); - if( Global::iMultisampling ) { + if( Global.iMultisampling ) { ::glDisable( GL_MULTISAMPLE ); } ::glDisable( GL_FOG ); @@ -1028,7 +1048,7 @@ opengl_renderer::setup_units( bool const Diffuse, bool const Shadows, bool const select_unit( m_helpertextureunit ); if( ( true == Reflections ) - || ( ( true == Global::RenderShadows ) && ( true == Shadows ) && ( false == Global::bWireFrame ) ) ) { + || ( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) ) { // we need to have texture on the helper for either the reflection and shadow generation (or both) if( true == m_environmentcubetexturesupport ) { // bind dynamic environment cube if it's enabled... @@ -1051,7 +1071,7 @@ opengl_renderer::setup_units( bool const Diffuse, bool const Shadows, bool const } } - if( ( true == Global::RenderShadows ) && ( true == Shadows ) && ( false == Global::bWireFrame ) ) { + if( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) { ::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE ); ::glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, glm::value_ptr( m_shadowcolor ) ); @@ -1107,9 +1127,9 @@ opengl_renderer::setup_units( bool const Diffuse, bool const Shadows, bool const // shadow texture unit. // interpolates between primary colour and the previous unit, which should hold darkened variant of the primary colour if( m_shadowtextureunit >= 0 ) { - if( ( true == Global::RenderShadows ) + if( ( true == Global.RenderShadows ) && ( true == Shadows ) - && ( false == Global::bWireFrame ) + && ( false == Global.bWireFrame ) && ( m_shadowcolor != colors::white ) ) { select_unit( m_shadowtextureunit ); @@ -1211,8 +1231,8 @@ void opengl_renderer::setup_shadow_map( GLuint const Texture, glm::mat4 const &Transformation ) { if( ( m_shadowtextureunit == -1 ) - || ( false == Global::RenderShadows ) - || ( true == Global::bWireFrame ) + || ( false == Global.RenderShadows ) + || ( true == Global.bWireFrame ) || ( m_shadowcolor == colors::white ) ) { // shadows are off return; @@ -1241,9 +1261,9 @@ opengl_renderer::switch_units( bool const Diffuse, bool const Shadows, bool cons select_unit( m_helpertextureunit ); if( ( true == Reflections ) - || ( ( true == Global::RenderShadows ) + || ( ( true == Global.RenderShadows ) && ( true == Shadows ) - && ( false == Global::bWireFrame ) + && ( false == Global.bWireFrame ) && ( m_shadowcolor != colors::white ) ) ) { if( true == m_environmentcubetexturesupport ) { ::glEnable( GL_TEXTURE_CUBE_MAP ); @@ -1263,7 +1283,7 @@ opengl_renderer::switch_units( bool const Diffuse, bool const Shadows, bool cons } // shadow texture unit. if( m_shadowtextureunit >= 0 ) { - if( ( true == Global::RenderShadows ) && ( true == Shadows ) && ( false == Global::bWireFrame ) ) { + if( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) { select_unit( m_shadowtextureunit ); ::glEnable( GL_TEXTURE_2D ); @@ -1312,6 +1332,33 @@ opengl_renderer::setup_shadow_color( glm::vec4 const &Shadowcolor ) { select_unit( m_diffusetextureunit ); } +void +opengl_renderer::setup_environment_light( TEnvironmentType const Environment ) { + + if( m_environment == Environment ) { return; } + + switch( Environment ) { + case e_flat: { + m_sunlight.apply_intensity(); + m_environment = e_flat; + break; + } + case e_canyon: { + m_sunlight.apply_intensity( 0.4f ); + m_environment = Environment; + break; + } + case e_tunnel: { + m_sunlight.apply_intensity( 0.2f ); + m_environment = Environment; + break; + } + default: { + break; + } + } +} + bool opengl_renderer::Render( world_environment *Environment ) { @@ -1328,9 +1375,9 @@ opengl_renderer::Render( world_environment *Environment ) { // soften shadows depending on sky overcast factor m_shadowcolor = glm::min( colors::white, - m_shadowcolor + glm::vec4{ glm::vec3{ 0.5f * Global::Overcast }, 1.f } ); + m_shadowcolor + glm::vec4{ glm::vec3{ 0.5f * Global.Overcast }, 1.f } ); - if( Global::bWireFrame ) { + if( Global.bWireFrame ) { // bez nieba w trybie rysowania linii return false; } @@ -1343,7 +1390,7 @@ opengl_renderer::Render( world_environment *Environment ) { // skydome Environment->m_skydome.Render(); - if( true == Global::bUseVBO ) { + if( true == Global.bUseVBO ) { // skydome uses a custom vbo which could potentially confuse the main geometry system. hardly elegant but, eh gfx::opengl_vbogeometrybank::reset(); } @@ -1352,7 +1399,7 @@ opengl_renderer::Render( world_environment *Environment ) { // setup ::glPushMatrix(); ::glRotatef( Environment->m_stars.m_latitude, 1.f, 0.f, 0.f ); // ustawienie osi OY na północ - ::glRotatef( -std::fmod( (float)Global::fTimeAngleDeg, 360.f ), 0.f, 1.f, 0.f ); // obrót dobowy osi OX + ::glRotatef( -std::fmod( (float)Global.fTimeAngleDeg, 360.f ), 0.f, 1.f, 0.f ); // obrót dobowy osi OX ::glPointSize( 2.f ); // render GfxRenderer.Render( Environment->m_stars.m_stars, nullptr, 1.0 ); @@ -1407,7 +1454,7 @@ opengl_renderer::Render( world_environment *Environment ) { { Bind_Texture( m_moontexture ); glm::vec3 mooncolor( 255.0f / 255.0f, 242.0f / 255.0f, 231.0f / 255.0f ); - ::glColor4f( mooncolor.x, mooncolor.y, mooncolor.z, static_cast( 1.0 - Global::fLuminance * 0.5 ) ); + ::glColor4f( mooncolor.x, mooncolor.y, mooncolor.z, static_cast( 1.0 - Global.fLuminance * 0.5 ) ); auto const moonposition = modelview * glm::vec4( Environment->m_moon.getDirection(), 1.0f ); ::glPushMatrix(); @@ -1453,7 +1500,7 @@ opengl_renderer::Render( world_environment *Environment ) { GL_LIGHT_MODEL_AMBIENT, glm::value_ptr( interpolate( Environment->m_skydome.GetAverageColor(), suncolor, duskfactor * 0.25f ) - * interpolate( 1.f, 0.35f, Global::Overcast / 2.f ) // overcast darkens the clouds + * interpolate( 1.f, 0.35f, Global.Overcast / 2.f ) // overcast darkens the clouds * 2.5f // arbitrary adjustment factor ) ); // render @@ -1465,8 +1512,8 @@ opengl_renderer::Render( world_environment *Environment ) { ::glDisable( GL_LIGHTING ); } - Global::DayLight.apply_angle(); - Global::DayLight.apply_intensity(); + m_sunlight.apply_angle(); + m_sunlight.apply_intensity(); ::glPopMatrix(); ::glDepthMask( GL_TRUE ); @@ -1523,7 +1570,7 @@ void opengl_renderer::Bind_Material( material_handle const Material ) { auto const &material = m_materials.material( Material ); - if( false == Global::BasicRenderer ) { + if( false == Global.BasicRenderer ) { m_textures.bind( textureunit::normals, material.texture2 ); } m_textures.bind( textureunit::diffuse, material.texture1 ); @@ -1569,7 +1616,7 @@ opengl_renderer::Render( scene::basic_region *Region ) { glm::vec3 const cameraposition { m_renderpass.camera.position() }; auto const camerax = static_cast( std::floor( cameraposition.x / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2 ) ); auto const cameraz = static_cast( std::floor( cameraposition.z / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2 ) ); - int const segmentcount = 2 * static_cast( std::ceil( m_renderpass.draw_range * Global::fDistanceFactor / scene::EU07_SECTIONSIZE ) ); + int const segmentcount = 2 * static_cast( std::ceil( m_renderpass.draw_range * Global.fDistanceFactor / scene::EU07_SECTIONSIZE ) ); int const originx = camerax - segmentcount / 2; int const originz = cameraz - segmentcount / 2; @@ -1590,6 +1637,7 @@ opengl_renderer::Render( scene::basic_region *Region ) { switch( m_renderpass.draw_mode ) { case rendermode::color: { + m_sunlight = Global.DayLight; Update_Lights( simulation::Lights ); Render( std::begin( m_sectionqueue ), std::end( m_sectionqueue ) ); @@ -1851,11 +1899,11 @@ opengl_renderer::Render( scene::shape_node const &Shape, bool const Ignorerange switch( m_renderpass.draw_mode ) { case rendermode::shadows: { // 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees - distancesquared = SquareMagnitude( ( data.area.center - Global::pCameraPosition ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( data.area.center - Global.pCameraPosition ) / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - distancesquared = SquareMagnitude( ( data.area.center - m_renderpass.camera.position() ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = glm::length2( ( data.area.center - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -1875,7 +1923,7 @@ opengl_renderer::Render( scene::shape_node const &Shape, bool const Ignorerange // NOTE: ambient component is set by diffuse component // NOTE: for the time being non-instanced shapes are rendered without specular component due to wrong/arbitrary values set in legacy scenarios // TBD, TODO: find a way to resolve this with the least amount of tears? - ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( data.lighting.specular * Global::DayLight.specular.a * m_specularopaquescalefactor ) ); + ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( data.lighting.specular * Global.DayLight.specular.a * m_specularopaquescalefactor ) ); */ break; } @@ -1905,11 +1953,11 @@ opengl_renderer::Render( TAnimModel *Instance ) { switch( m_renderpass.draw_mode ) { case rendermode::shadows: { // 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees - distancesquared = SquareMagnitude( ( Instance->location() - Global::pCameraPosition ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( Instance->location() - Global.pCameraPosition ) / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - distancesquared = SquareMagnitude( ( Instance->location() - m_renderpass.camera.position() ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( Instance->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -1959,11 +2007,11 @@ opengl_renderer::Render( TDynamicObject *Dynamic ) { float squaredistance; switch( m_renderpass.draw_mode ) { case rendermode::shadows: { - squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global::pCameraPosition } } / Global::ZoomFactor ) / Global::fDistanceFactor; + squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global.pCameraPosition } } / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - squaredistance = glm::length2( glm::vec3{ originoffset } / Global::ZoomFactor ) / Global::fDistanceFactor; + squaredistance = glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -1978,7 +2026,7 @@ opengl_renderer::Render( TDynamicObject *Dynamic ) { case rendermode::color: { if( Dynamic->fShade > 0.0f ) { // change light level based on light level of the occupied track - Global::DayLight.apply_intensity( Dynamic->fShade ); + m_sunlight.apply_intensity( Dynamic->fShade ); } m_renderspecular = true; // vehicles are rendered with specular component. static models without, at least for the time being // render @@ -2011,7 +2059,7 @@ opengl_renderer::Render( TDynamicObject *Dynamic ) { m_renderspecular = false; if( Dynamic->fShade > 0.0f ) { // restore regular light level - Global::DayLight.apply_intensity(); + m_sunlight.apply_intensity(); } break; } @@ -2077,7 +2125,7 @@ opengl_renderer::Render_cab( TDynamicObject const *Dynamic, bool const Alpha ) { // render path specific setup: if( Dynamic->fShade > 0.0f ) { // change light level based on light level of the occupied track - Global::DayLight.apply_intensity( Dynamic->fShade ); + m_sunlight.apply_intensity( Dynamic->fShade ); } if( Dynamic->InteriorLightLevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place @@ -2095,7 +2143,7 @@ opengl_renderer::Render_cab( TDynamicObject const *Dynamic, bool const Alpha ) { // post-render restore if( Dynamic->fShade > 0.0f ) { // change light level based on light level of the occupied track - Global::DayLight.apply_intensity(); + m_sunlight.apply_intensity(); } if( Dynamic->InteriorLightLevel > 0.0f ) { // reset the overall ambient @@ -2242,14 +2290,14 @@ opengl_renderer::Render( TSubModel *Submodel ) { } // ...colors... ::glColor3fv( glm::value_ptr( Submodel->f4Diffuse ) ); // McZapkie-240702: zamiast ub - if( ( true == m_renderspecular ) && ( Global::DayLight.specular.a > 0.01f ) ) { + if( ( true == m_renderspecular ) && ( Global.DayLight.specular.a > 0.01f ) ) { // specular strength in legacy models is set uniformly to 150, 150, 150 so we scale it down for opaque elements - ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * Global::DayLight.specular.a * m_specularopaquescalefactor ) ); + ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * Global.DayLight.specular.a * m_specularopaquescalefactor ) ); ::glEnable( GL_RESCALE_NORMAL ); } // ...luminance auto const unitstate = m_unitstate; - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // zeby swiecilo na kolorowo ::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( Submodel->f4Diffuse * Submodel->f4Emision.a ) ); // disable shadows so they don't obstruct self-lit items @@ -2263,10 +2311,10 @@ opengl_renderer::Render( TSubModel *Submodel ) { m_geometry.draw( Submodel->m_geometry ); // post-draw reset - if( ( true == m_renderspecular ) && ( Global::DayLight.specular.a > 0.01f ) ) { + if( ( true == m_renderspecular ) && ( Global.DayLight.specular.a > 0.01f ) ) { ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( colors::none ) ); } - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // restore default (lack of) brightness ::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( colors::none ) ); /* @@ -2402,7 +2450,7 @@ opengl_renderer::Render( TSubModel *Submodel ) { // colour points are only rendered in colour mode(s) case rendermode::color: case rendermode::reflections: { - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // material configuration: ::glPushAttrib( GL_ENABLE_BIT | GL_CURRENT_BIT ); @@ -2456,7 +2504,7 @@ opengl_renderer::Render( TTrack *Track ) { switch( m_renderpass.draw_mode ) { case rendermode::color: case rendermode::reflections: { - Track->EnvironmentSet(); + setup_environment_light( Track->eEnvironment ); if( Track->m_material1 != 0 ) { Bind_Material( Track->m_material1 ); m_geometry.draw( std::begin( Track->Geometry1 ), std::end( Track->Geometry1 ) ); @@ -2465,7 +2513,7 @@ opengl_renderer::Render( TTrack *Track ) { Bind_Material( Track->m_material2 ); m_geometry.draw( std::begin( Track->Geometry2 ), std::end( Track->Geometry2 ) ); } - Track->EnvironmentReset(); + setup_environment_light(); break; } case rendermode::shadows: { @@ -2529,10 +2577,10 @@ opengl_renderer::Render( scene::basic_cell::path_sequence::const_iterator First, switch( m_renderpass.draw_mode ) { case rendermode::color: case rendermode::reflections: { - track->EnvironmentSet(); + setup_environment_light( track->eEnvironment ); Bind_Material( track->m_material1 ); m_geometry.draw( std::begin( track->Geometry1 ), std::end( track->Geometry1 ) ); - track->EnvironmentReset(); + setup_environment_light(); break; } case rendermode::shadows: { @@ -2567,10 +2615,10 @@ opengl_renderer::Render( scene::basic_cell::path_sequence::const_iterator First, switch( m_renderpass.draw_mode ) { case rendermode::color: case rendermode::reflections: { - track->EnvironmentSet(); + setup_environment_light( track->eEnvironment ); Bind_Material( track->m_material2 ); m_geometry.draw( std::begin( track->Geometry2 ), std::end( track->Geometry2 ) ); - track->EnvironmentReset(); + setup_environment_light(); break; } case rendermode::shadows: { @@ -2712,7 +2760,7 @@ opengl_renderer::Render_Alpha( cell_sequence::reverse_iterator First, cell_seque ::glPushMatrix(); auto const originoffset { cell->m_area.center - m_renderpass.camera.position() }; ::glTranslated( originoffset.x, originoffset.y, originoffset.z ); - if( !Global::bSmoothTraction ) { + if( !Global.bSmoothTraction ) { // na liniach kiepsko wygląda - robi gradient ::glDisable( GL_LINE_SMOOTH ); } @@ -2722,7 +2770,7 @@ opengl_renderer::Render_Alpha( cell_sequence::reverse_iterator First, cell_seque for( auto &lines : cell->m_lines ) { Render_Alpha( lines ); } // post-render cleanup ::glLineWidth( 1.0 ); - if( !Global::bSmoothTraction ) { + if( !Global.bSmoothTraction ) { ::glEnable( GL_LINE_SMOOTH ); } ::glPopMatrix(); @@ -2746,11 +2794,11 @@ opengl_renderer::Render_Alpha( TAnimModel *Instance ) { switch( m_renderpass.draw_mode ) { case rendermode::shadows: { // 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees - distancesquared = SquareMagnitude( ( Instance->location() - Global::pCameraPosition ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( Instance->location() - Global.pCameraPosition ) / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - distancesquared = SquareMagnitude( ( Instance->location() - m_renderpass.camera.position() ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = glm::length2( ( Instance->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -2778,11 +2826,11 @@ opengl_renderer::Render_Alpha( TTraction *Traction ) { switch( m_renderpass.draw_mode ) { case rendermode::shadows: { // 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees - distancesquared = SquareMagnitude( ( Traction->location() - Global::pCameraPosition ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( Traction->location() - Global.pCameraPosition ) / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - distancesquared = SquareMagnitude( ( Traction->location() - m_renderpass.camera.position() ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = glm::length2( ( Traction->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -2839,11 +2887,11 @@ opengl_renderer::Render_Alpha( scene::lines_node const &Lines ) { switch( m_renderpass.draw_mode ) { case rendermode::shadows: { // 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees - distancesquared = SquareMagnitude( ( data.area.center - Global::pCameraPosition ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = Math3D::SquareMagnitude( ( data.area.center - Global.pCameraPosition ) / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - distancesquared = SquareMagnitude( ( data.area.center - m_renderpass.camera.position() ) / Global::ZoomFactor ) / Global::fDistanceFactor; + distancesquared = glm::length2( ( data.area.center - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -2867,7 +2915,7 @@ opengl_renderer::Render_Alpha( scene::lines_node const &Lines ) { ::glColor4fv( glm::value_ptr( glm::vec4{ - glm::vec3{ data.lighting.diffuse * Global::DayLight.ambient }, // w zaleznosci od koloru swiatla + glm::vec3{ data.lighting.diffuse * Global.DayLight.ambient }, // w zaleznosci od koloru swiatla std::min( 1.f, linealpha ) } ) ); // render m_geometry.draw( data.geometry ); @@ -2887,11 +2935,11 @@ opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) { float squaredistance; switch( m_renderpass.draw_mode ) { case rendermode::shadows: { - squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global::pCameraPosition } } / Global::ZoomFactor ) / Global::fDistanceFactor; + squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global.pCameraPosition } } / Global.ZoomFactor ) / Global.fDistanceFactor; break; } default: { - squaredistance = glm::length2( glm::vec3{ originoffset } / Global::ZoomFactor ) / Global::fDistanceFactor; + squaredistance = glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) / Global.fDistanceFactor; break; } } @@ -2903,7 +2951,7 @@ opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) { if( Dynamic->fShade > 0.0f ) { // change light level based on light level of the occupied track - Global::DayLight.apply_intensity( Dynamic->fShade ); + m_sunlight.apply_intensity( Dynamic->fShade ); } m_renderspecular = true; @@ -2937,7 +2985,7 @@ opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) { m_renderspecular = false; if( Dynamic->fShade > 0.0f ) { // restore regular light level - Global::DayLight.apply_intensity(); + m_sunlight.apply_intensity(); } ::glPopMatrix(); @@ -3052,12 +3100,12 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { } // ...colors... ::glColor3fv( glm::value_ptr( Submodel->f4Diffuse ) ); // McZapkie-240702: zamiast ub - if( ( true == m_renderspecular ) && ( Global::DayLight.specular.a > 0.01f ) ) { - ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * Global::DayLight.specular.a * m_speculartranslucentscalefactor ) ); + if( ( true == m_renderspecular ) && ( Global.DayLight.specular.a > 0.01f ) ) { + ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * Global.DayLight.specular.a * m_speculartranslucentscalefactor ) ); } // ...luminance auto const unitstate = m_unitstate; - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // zeby swiecilo na kolorowo ::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( Submodel->f4Diffuse * Submodel->f4Emision.a ) ); // disable shadows so they don't obstruct self-lit items @@ -3071,10 +3119,10 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { m_geometry.draw( Submodel->m_geometry ); // post-draw reset - if( ( true == m_renderspecular ) && ( Global::DayLight.specular.a > 0.01f ) ) { + if( ( true == m_renderspecular ) && ( Global.DayLight.specular.a > 0.01f ) ) { ::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( colors::none ) ); } - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // restore default (lack of) brightness ::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( colors::none ) ); /* @@ -3122,7 +3170,7 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { } else if( Submodel->eType == TP_FREESPOTLIGHT ) { - if( Global::fLuminance < Submodel->fLight ) { + if( Global.fLuminance < Submodel->fLight ) { // NOTE: we're forced here to redo view angle calculations etc, because this data isn't instanced but stored along with the single mesh // TODO: separate instance data from reusable geometry auto const &modelview = OpenGLMatrices.data( GL_MODELVIEW ); @@ -3137,14 +3185,14 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel ) { float glarelevel = 0.6f; // luminosity at night is at level of ~0.1, so the overall resulting transparency in clear conditions is ~0.5 at full 'brightness' if( Submodel->fCosViewAngle > Submodel->fCosFalloffAngle ) { // only bother if the viewer is inside the visibility cone - if( Global::Overcast > 1.0 ) { + if( Global.Overcast > 1.0 ) { // increase the glare in rainy/foggy conditions - glarelevel += std::max( 0.f, 0.5f * ( Global::Overcast - 1.f ) ); + glarelevel += std::max( 0.f, 0.5f * ( Global.Overcast - 1.f ) ); } // scale it down based on view angle glarelevel *= ( Submodel->fCosViewAngle - Submodel->fCosFalloffAngle ) / ( 1.0f - Submodel->fCosFalloffAngle ); // reduce the glare in bright daylight - glarelevel = clamp( glarelevel - static_cast(Global::fLuminance), 0.f, 1.f ); + glarelevel = clamp( glarelevel - static_cast(Global.fLuminance), 0.f, 1.f ); if( glarelevel > 0.0f ) { // setup @@ -3243,15 +3291,15 @@ opengl_renderer::Update_Pick_Control() { // determine point to examine glm::dvec2 mousepos; glfwGetCursorPos( m_window, &mousepos.x, &mousepos.y ); - mousepos.y = Global::iWindowHeight - mousepos.y; // cursor coordinates are flipped compared to opengl + mousepos.y = Global.iWindowHeight - mousepos.y; // cursor coordinates are flipped compared to opengl #ifdef EU07_USE_PICKING_FRAMEBUFFER glm::ivec2 pickbufferpos; if( true == m_framebuffersupport ) { // ::glReadBuffer( GL_COLOR_ATTACHMENT0_EXT ); pickbufferpos = glm::ivec2{ - mousepos.x * EU07_PICKBUFFERSIZE / std::max( 1, Global::iWindowWidth ), - mousepos.y * EU07_PICKBUFFERSIZE / std::max( 1, Global::iWindowHeight ) }; + mousepos.x * EU07_PICKBUFFERSIZE / std::max( 1, Global.iWindowWidth ), + mousepos.y * EU07_PICKBUFFERSIZE / std::max( 1, Global.iWindowHeight ) }; } else { // ::glReadBuffer( GL_BACK ); @@ -3290,15 +3338,15 @@ opengl_renderer::Update_Pick_Node() { // determine point to examine glm::dvec2 mousepos; glfwGetCursorPos( m_window, &mousepos.x, &mousepos.y ); - mousepos.y = Global::iWindowHeight - mousepos.y; // cursor coordinates are flipped compared to opengl + mousepos.y = Global.iWindowHeight - mousepos.y; // cursor coordinates are flipped compared to opengl #ifdef EU07_USE_PICKING_FRAMEBUFFER glm::ivec2 pickbufferpos; if( true == m_framebuffersupport ) { // ::glReadBuffer( GL_COLOR_ATTACHMENT0_EXT ); pickbufferpos = glm::ivec2{ - mousepos.x * EU07_PICKBUFFERSIZE / Global::iWindowWidth, - mousepos.y * EU07_PICKBUFFERSIZE / Global::iWindowHeight + mousepos.x * EU07_PICKBUFFERSIZE / Global.iWindowWidth, + mousepos.y * EU07_PICKBUFFERSIZE / Global.iWindowHeight }; } else { @@ -3347,31 +3395,31 @@ opengl_renderer::Update( double const Deltatime ) { if( framerate > 90.0 ) { targetfactor = 3.0f; } else if( framerate > 60.0 ) { targetfactor = 1.5f; } else if( framerate > 30.0 ) { targetfactor = 1.25; } - else { targetfactor = std::max( Global::iWindowHeight / 768.f, 1.f ); } + else { targetfactor = std::max( Global.iWindowHeight / 768.f, 1.f ); } - if( targetfactor > Global::fDistanceFactor ) { + if( targetfactor > Global.fDistanceFactor ) { - Global::fDistanceFactor = std::min( targetfactor, Global::fDistanceFactor + 0.05f ); + Global.fDistanceFactor = std::min( targetfactor, Global.fDistanceFactor + 0.05f ); } - else if( targetfactor < Global::fDistanceFactor ) { + else if( targetfactor < Global.fDistanceFactor ) { - Global::fDistanceFactor = std::max( targetfactor, Global::fDistanceFactor - 0.05f ); + Global.fDistanceFactor = std::max( targetfactor, Global.fDistanceFactor - 0.05f ); } - if( ( framerate < 15.0 ) && ( Global::iSlowMotion < 7 ) ) { - Global::iSlowMotion = ( Global::iSlowMotion << 1 ) + 1; // zapalenie kolejnego bitu - if( Global::iSlowMotionMask & 1 ) - if( Global::iMultisampling ) // a multisampling jest włączony + if( ( framerate < 15.0 ) && ( Global.iSlowMotion < 7 ) ) { + Global.iSlowMotion = ( Global.iSlowMotion << 1 ) + 1; // zapalenie kolejnego bitu + if( Global.iSlowMotionMask & 1 ) + if( Global.iMultisampling ) // a multisampling jest włączony ::glDisable( GL_MULTISAMPLE ); // wyłączenie multisamplingu powinno poprawić FPS } - else if( ( framerate > 20.0 ) && Global::iSlowMotion ) { // FPS się zwiększył, można włączyć bajery - Global::iSlowMotion = ( Global::iSlowMotion >> 1 ); // zgaszenie bitu - if( Global::iSlowMotion == 0 ) // jeśli jest pełna prędkość - if( Global::iMultisampling ) // a multisampling jest włączony + else if( ( framerate > 20.0 ) && Global.iSlowMotion ) { // FPS się zwiększył, można włączyć bajery + Global.iSlowMotion = ( Global.iSlowMotion >> 1 ); // zgaszenie bitu + if( Global.iSlowMotion == 0 ) // jeśli jest pełna prędkość + if( Global.iMultisampling ) // a multisampling jest włączony ::glEnable( GL_MULTISAMPLE ); } - if( ( true == Global::ResourceSweep ) + if( ( true == Global.ResourceSweep ) && ( true == World.InitPerformed() ) ) { // garbage collection m_geometry.update(); @@ -3382,7 +3430,7 @@ opengl_renderer::Update( double const Deltatime ) { m_debugtimestext += m_textures.info(); } - if( ( true == Global::ControlPicking ) + if( ( true == Global.ControlPicking ) && ( false == FreeFlyModeFlag ) ) { Update_Pick_Control(); } @@ -3390,7 +3438,7 @@ opengl_renderer::Update( double const Deltatime ) { m_pickcontrolitem = nullptr; } // temporary conditions for testing. eventually will be coupled with editor mode - if( ( true == Global::ControlPicking ) + if( ( true == Global.ControlPicking ) && ( true == DebugModeFlag ) && ( true == FreeFlyModeFlag ) ) { Update_Pick_Node(); @@ -3403,7 +3451,7 @@ opengl_renderer::Update( double const Deltatime ) { if( glerror != GL_NO_ERROR ) { std::string glerrorstring( ( char * )::gluErrorString( glerror ) ); win1250_to_ascii( glerrorstring ); - Global::LastGLError = std::to_string( glerror ) + " (" + glerrorstring + ")"; + Global.LastGLError = std::to_string( glerror ) + " (" + glerrorstring + ")"; } } @@ -3456,10 +3504,10 @@ opengl_renderer::Update_Lights( light_array &Lights ) { continue; } // if the light passed tests so far, it's good enough - renderlight->set_position( lightoffset ); + renderlight->position = lightoffset; renderlight->direction = scenelight.direction; - auto luminance = static_cast( Global::fLuminance ); + auto luminance = static_cast( Global.fLuminance ); // adjust luminance level based on vehicle's location, e.g. tunnels auto const environment = scenelight.owner->fShade; if( environment > 0.f ) { @@ -3516,7 +3564,7 @@ opengl_renderer::Init_caps() { WriteLog( "Supported extensions: " + std::string((char *)glGetString( GL_EXTENSIONS )) ); - WriteLog( std::string("Render path: ") + ( Global::bUseVBO ? "VBO" : "Display lists" ) ); + WriteLog( std::string("Render path: ") + ( Global.bUseVBO ? "VBO" : "Display lists" ) ); if( GLEW_EXT_framebuffer_object ) { m_framebuffersupport = true; WriteLog( "Framebuffer objects enabled" ); @@ -3528,9 +3576,9 @@ opengl_renderer::Init_caps() { { GLint texturesize; ::glGetIntegerv( GL_MAX_TEXTURE_SIZE, &texturesize ); - Global::iMaxTextureSize = std::min( Global::iMaxTextureSize, texturesize ); - WriteLog( "Texture sizes capped at " + std::to_string( Global::iMaxTextureSize ) + " pixels" ); - m_shadowbuffersize = Global::shadowtune.map_size; + Global.iMaxTextureSize = std::min( Global.iMaxTextureSize, texturesize ); + WriteLog( "Texture sizes capped at " + std::to_string( Global.iMaxTextureSize ) + " pixels" ); + m_shadowbuffersize = Global.shadowtune.map_size; m_shadowbuffersize = std::min( m_shadowbuffersize, texturesize ); WriteLog( "Shadows map size capped at " + std::to_string( m_shadowbuffersize ) + " pixels" ); } @@ -3538,13 +3586,13 @@ opengl_renderer::Init_caps() { { GLint maxlights; ::glGetIntegerv( GL_MAX_LIGHTS, &maxlights ); - Global::DynamicLightCount = std::min( Global::DynamicLightCount, maxlights - 1 ); - WriteLog( "Dynamic light amount capped at " + std::to_string( Global::DynamicLightCount ) + " (" + std::to_string(maxlights) + " lights total supported by the gfx card)" ); + Global.DynamicLightCount = std::min( Global.DynamicLightCount, maxlights - 1 ); + WriteLog( "Dynamic light amount capped at " + std::to_string( Global.DynamicLightCount ) + " (" + std::to_string(maxlights) + " lights total supported by the gfx card)" ); } // select renderer mode - if( true == Global::BasicRenderer ) { + if( true == Global.BasicRenderer ) { WriteLog( "Basic renderer selected, shadow and reflection mapping will be disabled" ); - Global::RenderShadows = false; + Global.RenderShadows = false; m_diffusetextureunit = GL_TEXTURE0; m_helpertextureunit = -1; m_shadowtextureunit = -1; @@ -3555,8 +3603,8 @@ opengl_renderer::Init_caps() { ::glGetIntegerv( GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxtextureunits ); if( maxtextureunits < 4 ) { WriteLog( "Less than 4 texture units, shadow and reflection mapping will be disabled" ); - Global::BasicRenderer = true; - Global::RenderShadows = false; + Global.BasicRenderer = true; + Global.RenderShadows = false; m_diffusetextureunit = GL_TEXTURE0; m_helpertextureunit = -1; m_shadowtextureunit = -1; @@ -3564,8 +3612,8 @@ opengl_renderer::Init_caps() { } } - if( Global::iMultisampling ) { - WriteLog( "Using multisampling x" + std::to_string( 1 << Global::iMultisampling ) ); + if( Global.iMultisampling ) { + WriteLog( "Using multisampling x" + std::to_string( 1 << Global.iMultisampling ) ); } return true; diff --git a/renderer.h b/renderer.h index 50f35e99..517393e2 100644 --- a/renderer.h +++ b/renderer.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "GL/glew.h" #include "openglgeometrybank.h" #include "material.h" +#include "light.h" #include "lightarray.h" #include "dumb3d.h" #include "frustum.h" @@ -24,48 +25,19 @@ http://mozilla.org/MPL/2.0/. //#define EU07_USE_DEBUG_CABSHADOWMAP //#define EU07_USE_DEBUG_CAMERA -struct opengl_light { +struct opengl_light : public basic_light { - GLuint id{ (GLuint)-1 }; - glm::vec3 direction; - glm::vec4 - position { 0.f, 0.f, 0.f, 1.f }, // 4th parameter specifies directional(0) or omni-directional(1) light source - ambient { 0.f, 0.f, 0.f, 1.f }, - diffuse { 1.f, 1.f, 1.f, 1.f }, - specular { 1.f, 1.f, 1.f, 1.f }; + GLuint id { (GLuint)-1 }; - inline - void apply_intensity( float const Factor = 1.0f ) { + void + apply_intensity( float const Factor = 1.0f ); + void + apply_angle(); - if( Factor == 1.0 ) { - - glLightfv( id, GL_AMBIENT, glm::value_ptr(ambient) ); - glLightfv( id, GL_DIFFUSE, glm::value_ptr(diffuse) ); - glLightfv( id, GL_SPECULAR, glm::value_ptr(specular) ); - } - else { - // temporary light scaling mechanics (ultimately this work will be left to the shaders - glm::vec4 scaledambient( ambient.r * Factor, ambient.g * Factor, ambient.b * Factor, ambient.a ); - glm::vec4 scaleddiffuse( diffuse.r * Factor, diffuse.g * Factor, diffuse.b * Factor, diffuse.a ); - glm::vec4 scaledspecular( specular.r * Factor, specular.g * Factor, specular.b * Factor, specular.a ); - glLightfv( id, GL_AMBIENT, glm::value_ptr(scaledambient) ); - glLightfv( id, GL_DIFFUSE, glm::value_ptr(scaleddiffuse) ); - glLightfv( id, GL_SPECULAR, glm::value_ptr(scaledspecular) ); - } - } - inline - void apply_angle() { - - glLightfv( id, GL_POSITION, glm::value_ptr(position) ); - if( position.w == 1.f ) { - glLightfv( id, GL_SPOT_DIRECTION, glm::value_ptr(direction) ); - } - } - inline - void set_position( glm::vec3 const &Position ) { - - position = glm::vec4( Position, position.w ); - } + opengl_light & + operator=( basic_light const &Right ) { + basic_light::operator=( Right ); + return *this; } }; // encapsulates basic rendering setup. @@ -274,6 +246,8 @@ private: setup_shadow_map( GLuint const Texture, glm::mat4 const &Transformation ); void setup_shadow_color( glm::vec4 const &Shadowcolor ); + void + setup_environment_light( TEnvironmentType const Environment = e_flat ); void switch_units( bool const Diffuse, bool const Shadows, bool const Reflections ); // helper, texture manager method; activates specified texture unit @@ -343,6 +317,7 @@ private: gfx::geometrybank_manager m_geometry; material_manager m_materials; texture_manager m_textures; + opengl_light m_sunlight; opengllight_array m_lights; gfx::geometry_handle m_billboardgeometry { 0, 0 }; @@ -398,6 +373,7 @@ private: glm::vec4 m_baseambient { 0.0f, 0.0f, 0.0f, 1.0f }; glm::vec4 m_shadowcolor { 0.65f, 0.65f, 0.65f, 1.f }; + TEnvironmentType m_environment { e_flat }; float m_specularopaquescalefactor { 1.f }; float m_speculartranslucentscalefactor { 1.f }; bool m_renderspecular{ false }; // controls whether to include specular component in the calculations diff --git a/scene.cpp b/scene.cpp index 9487a7b6..f284a769 100644 --- a/scene.cpp +++ b/scene.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "timer.h" #include "logs.h" #include "sn_utils.h" +#include "renderer.h" namespace scene { @@ -54,7 +55,7 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex // jeśli ponad pantografem (bo może łapać druty spod wiaduktu) auto const fHorizontal = std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth; - if( ( Global::bEnableTraction ) + if( ( Global.bEnableTraction ) && ( fVertical < pantograph->PantWys - 0.15 ) ) { // jeśli drut jest niżej niż 15cm pod ślizgiem przełączamy w tryb połamania, o ile jedzie; // (bEnableTraction) aby dało się jeździć na koślawych sceneriach @@ -104,10 +105,10 @@ basic_cell::update_events() { // event launchers for( auto *launcher : m_eventlaunchers ) { if( ( true == launcher->check_conditions() ) - && ( SquareMagnitude( launcher->location() - Global::pCameraPosition ) < launcher->dRadius ) ) { + && ( SquareMagnitude( launcher->location() - Global.pCameraPosition ) < launcher->dRadius ) ) { WriteLog( "Eventlauncher " + launcher->name() ); - if( ( true == Global::shiftState ) + if( ( true == Global.shiftState ) && ( launcher->Event2 != nullptr ) ) { simulation::Events.AddToQuery( launcher->Event2, nullptr ); } @@ -827,9 +828,9 @@ void basic_region::update_events() { // render events and sounds from sectors near enough to the viewer auto const range = EU07_SECTIONSIZE; // arbitrary range - auto const §ionlist = sections( Global::pCameraPosition, range ); + auto const §ionlist = sections( Global.pCameraPosition, range ); for( auto *section : sectionlist ) { - section->update_events( Global::pCameraPosition, range ); + section->update_events( Global.pCameraPosition, range ); } } @@ -838,9 +839,9 @@ void basic_region::update_sounds() { // render events and sounds from sectors near enough to the viewer auto const range = 2750.f; // audible range of 100 db sound - auto const §ionlist = sections( Global::pCameraPosition, range ); + auto const §ionlist = sections( Global.pCameraPosition, range ); for( auto *section : sectionlist ) { - section->update_sounds( Global::pCameraPosition, range ); + section->update_sounds( Global.pCameraPosition, range ); } } @@ -872,7 +873,7 @@ basic_region::serialize( std::string const &Scenariofile ) const { // trim leading $ char rainsted utility may add to the base name for modified .scn files filename.erase( 0, 1 ); } - filename = Global::asCurrentSceneryPath + filename; + filename = Global.asCurrentSceneryPath + filename; if( ( filename.rfind( '.' ) != std::string::npos ) && ( filename.rfind( '.' ) != filename.rfind( ".." ) + 1 ) ) { // trim extension, it's typically going to be for different file type @@ -915,7 +916,7 @@ basic_region::deserialize( std::string const &Scenariofile ) { // trim leading $ char rainsted utility may add to the base name for modified .scn files filename.erase( 0, 1 ); } - filename = Global::asCurrentSceneryPath + filename; + filename = Global.asCurrentSceneryPath + filename; if( ( filename.rfind( '.' ) != std::string::npos ) && ( filename.rfind( '.' ) != filename.rfind( ".." ) + 1 ) ) { // trim extension, it's typically going to be for different file type diff --git a/scenenode.cpp b/scenenode.cpp index 4ebd51fe..588281c3 100644 --- a/scenenode.cpp +++ b/scenenode.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "scenenode.h" +#include "model3d.h" #include "renderer.h" #include "logs.h" #include "sn_utils.h" diff --git a/scenenode.h b/scenenode.h index df7c6f64..f99c361d 100644 --- a/scenenode.h +++ b/scenenode.h @@ -11,11 +11,10 @@ http://mozilla.org/MPL/2.0/. #include +#include "classes.h" #include "material.h" #include "vertex.h" #include "openglgeometrybank.h" -#include "parser.h" -#include "model3d.h" struct lighting_data { diff --git a/simulation.cpp b/simulation.cpp index 7fa73290..4140e443 100644 --- a/simulation.cpp +++ b/simulation.cpp @@ -10,9 +10,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "simulation.h" +#include "world.h" #include "globals.h" #include "logs.h" #include "uilayer.h" +#include "renderer.h" namespace simulation { @@ -44,7 +46,7 @@ state_manager::deserialize( std::string const &Scenariofile ) { importscratchpad.binary.terrain = Region->deserialize( Scenariofile ); } // NOTE: for the time being import from text format is a given, since we don't have full binary serialization - cParser scenarioparser( Scenariofile, cParser::buffer_FILE, Global::asCurrentSceneryPath, Global::bLoadTraction ); + cParser scenarioparser( Scenariofile, cParser::buffer_FILE, Global.asCurrentSceneryPath, Global.bLoadTraction ); if( false == scenarioparser.ok() ) { return false; } @@ -56,7 +58,7 @@ state_manager::deserialize( std::string const &Scenariofile ) { Region->serialize( Scenariofile ); } - Global::iPause &= ~0x10; // koniec pauzy wczytywania + Global.iPause &= ~0x10; // koniec pauzy wczytywania return true; } @@ -153,10 +155,10 @@ state_manager::deserialize_atmo( cParser &Input, scene::scratch_data &Scratchpad // fog range Input.getTokens( 2 ); Input - >> Global::fFogStart - >> Global::fFogEnd; + >> Global.fFogStart + >> Global.fFogEnd; - if( Global::fFogEnd > 0.0 ) { + if( Global.fFogEnd > 0.0 ) { // fog colour; optional legacy parameter, no longer used Input.getTokens( 3 ); } @@ -164,7 +166,7 @@ state_manager::deserialize_atmo( cParser &Input, scene::scratch_data &Scratchpad std::string token { Input.getToken() }; if( token != "endatmo" ) { // optional overcast parameter - Global::Overcast = clamp( std::stof( token ), 0.f, 2.f ); + Global.Overcast = clamp( std::stof( token ), 0.f, 2.f ); } while( ( false == token.empty() ) && ( token != "endatmo" ) ) { @@ -194,15 +196,15 @@ state_manager::deserialize_camera( cParser &Input, scene::scratch_data &Scratchp } } while( token.compare( "endcamera" ) != 0 ); if( into < 0 ) - into = ++Global::iCameraLast; + into = ++Global.iCameraLast; if( into < 10 ) { // przepisanie do odpowiedniego miejsca w tabelce - Global::FreeCameraInit[ into ] = xyz; - Global::FreeCameraInitAngle[ into ] = + Global.FreeCameraInit[ into ] = xyz; + Global.FreeCameraInitAngle[ into ] = Math3D::vector3( glm::radians( abc.x ), glm::radians( abc.y ), glm::radians( abc.z ) ); - Global::iCameraLast = into; // numer ostatniej + Global.iCameraLast = into; // numer ostatniej } /* // cleaned up version of the above. @@ -231,7 +233,7 @@ void state_manager::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { // config parameters (re)definition - Global::ConfigParse( Input ); + Global.ConfigParse( Input ); } void @@ -511,7 +513,7 @@ state_manager::deserialize_sky( cParser &Input, scene::scratch_data &Scratchpad // sky model Input.getTokens( 1 ); Input - >> Global::asSky; + >> Global.asSky; // anything else left in the section has no defined meaning skip_until( Input, "endsky" ); } @@ -627,7 +629,7 @@ state_manager::deserialize_path( cParser &Input, scene::scratch_data &Scratchpad TTraction * state_manager::deserialize_traction( cParser &Input, scene::scratch_data &Scratchpad, scene::node_data const &Nodedata ) { - if( false == Global::bLoadTraction ) { + if( false == Global.bLoadTraction ) { skip_until( Input, "endtraction" ); return nullptr; } @@ -645,7 +647,7 @@ state_manager::deserialize_traction( cParser &Input, scene::scratch_data &Scratc TTractionPowerSource * state_manager::deserialize_tractionpowersource( cParser &Input, scene::scratch_data &Scratchpad, scene::node_data const &Nodedata ) { - if( false == Global::bLoadTraction ) { + if( false == Global.bLoadTraction ) { skip_until( Input, "end" ); return nullptr; } diff --git a/sky.cpp b/sky.cpp index 7d6ee679..42a57cac 100644 --- a/sky.cpp +++ b/sky.cpp @@ -17,10 +17,10 @@ http://mozilla.org/MPL/2.0/. void TSky::Init() { - if( ( Global::asSky != "1" ) - && ( Global::asSky != "0" ) ) { + if( ( Global.asSky != "1" ) + && ( Global.asSky != "0" ) ) { - mdCloud = TModelsManager::GetModel( Global::asSky ); + mdCloud = TModelsManager::GetModel( Global.asSky ); } }; diff --git a/sky.h b/sky.h index ca48434e..a2e8b76f 100644 --- a/sky.h +++ b/sky.h @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "Model3d.h" +#include "classes.h" class TSky { diff --git a/skydome.cpp b/skydome.cpp index 984e1e19..18b90505 100644 --- a/skydome.cpp +++ b/skydome.cpp @@ -2,7 +2,7 @@ #include "stdafx.h" #include "skydome.h" #include "color.h" -#include "usefull.h" +#include "utilities.h" // sky gradient based on "A practical analytic model for daylight" // by A. J. Preetham Peter Shirley Brian Smits (University of Utah) @@ -283,9 +283,9 @@ void CSkyDome::RebuildColors() { float const Z = ((1.0f - x - y) / y) * Y; colorconverter = glm::vec3( X, Y, Z ); - color = XYZtoRGB( colorconverter ); + color = colors::XYZtoRGB( colorconverter ); - colorconverter = RGBtoHSV(color); + colorconverter = colors::RGBtoHSV(color); if ( m_linearexpcontrol ) { // linear scale colorconverter.z *= m_expfactor; @@ -309,9 +309,9 @@ void CSkyDome::RebuildColors() { float const shiftfactor = clamp( interpolate(heightbasedphase, sunbasedphase, sunbasedphase), 0.0f, 1.0f ); // h = 210 makes for 'typical' sky tone shiftedcolor = glm::vec3( 210.0f, colorconverter.y, colorconverter.z ); - shiftedcolor = HSVtoRGB( shiftedcolor ); + shiftedcolor = colors::HSVtoRGB( shiftedcolor ); - color = HSVtoRGB(colorconverter); + color = colors::HSVtoRGB(colorconverter); color = interpolate( color, shiftedcolor, shiftfactor ); /* diff --git a/sound.cpp b/sound.cpp index c101e1d9..c74af434 100644 --- a/sound.cpp +++ b/sound.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "globals.h" #include "world.h" #include "train.h" +#include "dynobj.h" // constructors sound_source::sound_source( sound_placement const Placement, float const Range ) : @@ -154,7 +155,7 @@ sound_source::deserialize_filename( cParser &Input ) { filenames.emplace_back( token ); } if( false == filenames.empty() ) { - std::shuffle( std::begin( filenames ), std::end( filenames ), Global::random_engine ); + std::shuffle( std::begin( filenames ), std::end( filenames ), Global.random_engine ); return filenames.front(); } else { @@ -279,7 +280,7 @@ sound_source::deserialize_soundset( cParser &Input ) { soundsets.emplace_back( token ); } if( false == soundsets.empty() ) { - std::shuffle( std::begin( soundsets ), std::end( soundsets ), Global::random_engine ); + std::shuffle( std::begin( soundsets ), std::end( soundsets ), Global.random_engine ); return deserialize_soundset( cParser( soundsets.front() ) ); } } @@ -300,7 +301,7 @@ sound_source::copy_sounds( sound_source const &Source ) { void sound_source::play( int const Flags ) { - if( ( false == Global::bSoundEnabled ) + if( ( false == Global.bSoundEnabled ) || ( true == empty() ) ) { // if the sound is disabled altogether or nothing can be emitted from this source, no point wasting time return; @@ -311,7 +312,7 @@ sound_source::play( int const Flags ) { if( m_range > 0 ) { auto const cutoffrange { m_range * 5 }; - if( glm::length2( location() - glm::dvec3 { Global::pCameraPosition } ) > std::min( 2750.f * 2750.f, cutoffrange * cutoffrange ) ) { + if( glm::length2( location() - glm::dvec3 { Global.pCameraPosition } ) > std::min( 2750.f * 2750.f, cutoffrange * cutoffrange ) ) { // while we drop sounds from beyond sensible and/or audible range // we act as if it was activated normally, meaning no need to include the opening bookend in subsequent calls m_playbeginning = false; @@ -825,17 +826,17 @@ sound_source::update_soundproofing() { // NOTE, HACK: current cab id can vary from -1 to +1, and we use another higher priority value for open cab window // we use this as modifier to force re-calculations when moving between compartments or changing window state int const activecab = ( - Global::CabWindowOpen ? 2 : + Global.CabWindowOpen ? 2 : FreeFlyModeFlag ? 0 : - ( Global::pWorld->train() ? - Global::pWorld->train()->Dynamic()->MoverParameters->ActiveCab : + ( Global.pWorld->train() ? + Global.pWorld->train()->Dynamic()->MoverParameters->ActiveCab : 0 ) ); // location-based gain factor: std::uintptr_t soundproofingstamp = reinterpret_cast( ( FreeFlyModeFlag ? nullptr : - ( Global::pWorld->train() ? - Global::pWorld->train()->Dynamic() : + ( Global.pWorld->train() ? + Global.pWorld->train()->Dynamic() : nullptr ) ) ) + activecab; @@ -849,7 +850,7 @@ sound_source::update_soundproofing() { } case sound_placement::external: { m_properties.soundproofing = ( - ( ( soundproofingstamp == 0 ) || ( true == Global::CabWindowOpen ) ) ? + ( ( soundproofingstamp == 0 ) || ( true == Global.CabWindowOpen ) ) ? EU07_SOUNDPROOFING_NONE : // listener outside or has a window open EU07_SOUNDPROOFING_STRONG ); // listener in a vehicle with windows shut break; @@ -858,7 +859,7 @@ sound_source::update_soundproofing() { m_properties.soundproofing = ( soundproofingstamp == 0 ? EU07_SOUNDPROOFING_STRONG : // listener outside HACK: won't be true if active vehicle has open window - ( Global::pWorld->train()->Dynamic() != m_owner ? + ( Global.pWorld->train()->Dynamic() != m_owner ? EU07_SOUNDPROOFING_STRONG : // in another vehicle ( activecab == 0 ? EU07_SOUNDPROOFING_STRONG : // listener in the engine compartment @@ -867,9 +868,9 @@ sound_source::update_soundproofing() { } case sound_placement::engine: { m_properties.soundproofing = ( - ( ( soundproofingstamp == 0 ) || ( true == Global::CabWindowOpen ) ) ? + ( ( soundproofingstamp == 0 ) || ( true == Global.CabWindowOpen ) ) ? EU07_SOUNDPROOFING_SOME : // listener outside or has a window open - ( Global::pWorld->train()->Dynamic() != m_owner ? + ( Global.pWorld->train()->Dynamic() != m_owner ? EU07_SOUNDPROOFING_STRONG : // in another vehicle ( activecab == 0 ? EU07_SOUNDPROOFING_NONE : // listener in the engine compartment diff --git a/stars.h b/stars.h index 7541bf77..5619a0c1 100644 --- a/stars.h +++ b/stars.h @@ -1,6 +1,6 @@ #pragma once -#include "Model3d.h" +#include "classes.h" ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/sun.cpp b/sun.cpp index 9e744635..5fdbabeb 100644 --- a/sun.cpp +++ b/sun.cpp @@ -3,7 +3,7 @@ #include "sun.h" #include "globals.h" #include "mtable.h" -#include "usefull.h" +#include "utilities.h" #include "world.h" ////////////////////////////////////////////////////////////////////////////////////////// @@ -50,7 +50,7 @@ void cSun::update() { move(); - glm::vec3 position( 0.f, 0.f, -2000.f * Global::fDistanceFactor ); + glm::vec3 position( 0.f, 0.f, -2000.f * Global.fDistanceFactor ); position = glm::rotateX( position, glm::radians( static_cast( m_body.elevref ) ) ); position = glm::rotateY( position, glm::radians( static_cast( -m_body.hrang ) ) ); diff --git a/uilayer.cpp b/uilayer.cpp index cf1f0fbc..c8711db2 100644 --- a/uilayer.cpp +++ b/uilayer.cpp @@ -3,7 +3,7 @@ #include "stdafx.h" #include "uilayer.h" #include "globals.h" -#include "usefull.h" +#include "utilities.h" #include "renderer.h" #include "logs.h" @@ -33,14 +33,14 @@ ui_layer::init( GLFWwindow *Window ) { 0, // width of font 0, // angle of escapement 0, // orientation angle - (Global::bGlutFont ? FW_MEDIUM : FW_HEAVY), // font weight + (Global.bGlutFont ? FW_MEDIUM : FW_HEAVY), // font weight FALSE, // italic FALSE, // underline FALSE, // strikeout DEFAULT_CHARSET, // character set identifier OUT_DEFAULT_PRECIS, // output precision CLIP_DEFAULT_PRECIS, // clipping precision - (Global::bGlutFont ? CLEARTYPE_QUALITY : PROOF_QUALITY), // output quality + (Global.bGlutFont ? CLEARTYPE_QUALITY : PROOF_QUALITY), // output quality DEFAULT_PITCH | FF_DONTCARE, // family and pitch "Lucida Console"); // font name ::SelectObject(hDC, font); // selects the font we want @@ -48,14 +48,14 @@ ui_layer::init( GLFWwindow *Window ) { // builds 96 characters starting at character 32 WriteLog( "Display Lists font used" ); //+AnsiString(glGetError()) WriteLog( "Font init OK" ); //+AnsiString(glGetError()) - Global::DLFont = true; + Global.DLFont = true; return true; } else { ErrorLog( "Font init failed" ); // return false; // NOTE: we report success anyway, given some cards can't produce fonts in this manner - Global::DLFont = false; + Global.DLFont = false; return true; } } @@ -65,7 +65,7 @@ ui_layer::render() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho( 0, std::max( 1, Global::iWindowWidth ), std::max( 1, Global::iWindowHeight ), 0, -1, 1 ); + glOrtho( 0, std::max( 1, Global.iWindowWidth ), std::max( 1, Global.iWindowHeight ), 0, -1, 1 ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); @@ -141,15 +141,15 @@ ui_layer::render_progress() { } if( false == m_progresstext.empty() ) { - float const screenratio = static_cast( Global::iWindowWidth ) / Global::iWindowHeight; + float const screenratio = static_cast( Global.iWindowWidth ) / Global.iWindowHeight; float const width = ( screenratio >= (4.0f/3.0f) ? - ( 4.0f / 3.0f ) * Global::iWindowHeight : - Global::iWindowWidth ); + ( 4.0f / 3.0f ) * Global.iWindowHeight : + Global.iWindowWidth ); float const heightratio = ( screenratio >= ( 4.0f / 3.0f ) ? - Global::iWindowHeight / 768.f : - Global::iWindowHeight / 768.f * screenratio / ( 4.0f / 3.0f ) ); + Global.iWindowHeight / 768.f : + Global.iWindowHeight / 768.f * screenratio / ( 4.0f / 3.0f ) ); float const height = 768.0f * heightratio; ::glColor4f( 216.0f / 255.0f, 216.0f / 255.0f, 216.0f / 255.0f, 1.0f ); @@ -157,8 +157,8 @@ ui_layer::render_progress() { auto const textwidth = m_progresstext.size() * charsize; auto const textheight = 12.0f; ::glRasterPos2f( - ( 0.5f * ( Global::iWindowWidth - width ) + origin.x * heightratio ) + ( ( size.x * heightratio - textwidth ) * 0.5f * heightratio ), - ( 0.5f * ( Global::iWindowHeight - height ) + origin.y * heightratio ) + ( charsize ) + ( ( size.y * heightratio - textheight ) * 0.5f * heightratio ) ); + ( 0.5f * ( Global.iWindowWidth - width ) + origin.x * heightratio ) + ( ( size.x * heightratio - textwidth ) * 0.5f * heightratio ), + ( 0.5f * ( Global.iWindowHeight - height ) + origin.y * heightratio ) + ( charsize ) + ( ( size.y * heightratio - textheight ) * 0.5f * heightratio ) ); print( m_progresstext ); } @@ -173,8 +173,8 @@ ui_layer::render_panels() { glPushAttrib( GL_ENABLE_BIT ); glDisable( GL_TEXTURE_2D ); - float const width = std::min( 4.f / 3.f, static_cast(Global::iWindowWidth) / std::max( 1, Global::iWindowHeight ) ) * Global::iWindowHeight; - float const height = Global::iWindowHeight / 768.f; + float const width = std::min( 4.f / 3.f, static_cast(Global.iWindowWidth) / std::max( 1, Global.iWindowHeight ) ) * Global.iWindowHeight; + float const height = Global.iWindowHeight / 768.f; for( auto const &panel : m_panels ) { @@ -183,7 +183,7 @@ ui_layer::render_panels() { ::glColor4fv( &line.color.x ); ::glRasterPos2f( - 0.5f * ( Global::iWindowWidth - width ) + panel->origin_x * height, + 0.5f * ( Global.iWindowWidth - width ) + panel->origin_x * height, panel->origin_y * height + 20.f * lineidx ); print( line.data ); ++lineidx; @@ -247,10 +247,10 @@ ui_layer::render_texture() { glBegin( GL_TRIANGLE_STRIP ); - glMultiTexCoord2f( m_textureunit, 0.f, 1.f ); glVertex2f( offset, Global::iWindowHeight - offset - size ); - glMultiTexCoord2f( m_textureunit, 0.f, 0.f ); glVertex2f( offset, Global::iWindowHeight - offset ); - glMultiTexCoord2f( m_textureunit, 1.f, 1.f ); glVertex2f( offset + size, Global::iWindowHeight - offset - size ); - glMultiTexCoord2f( m_textureunit, 1.f, 0.f ); glVertex2f( offset + size, Global::iWindowHeight - offset ); + glMultiTexCoord2f( m_textureunit, 0.f, 1.f ); glVertex2f( offset, Global.iWindowHeight - offset - size ); + glMultiTexCoord2f( m_textureunit, 0.f, 0.f ); glVertex2f( offset, Global.iWindowHeight - offset ); + glMultiTexCoord2f( m_textureunit, 1.f, 1.f ); glVertex2f( offset + size, Global.iWindowHeight - offset - size ); + glMultiTexCoord2f( m_textureunit, 1.f, 0.f ); glVertex2f( offset + size, Global.iWindowHeight - offset ); glEnd(); @@ -263,7 +263,7 @@ ui_layer::render_texture() { void ui_layer::print( std::string const &Text ) { - if( (false == Global::DLFont) + if( (false == Global.DLFont) || (true == Text.empty()) ) return; @@ -278,29 +278,29 @@ ui_layer::print( std::string const &Text ) void ui_layer::quad( float4 const &Coordinates, float4 const &Color ) { - float const screenratio = static_cast( Global::iWindowWidth ) / Global::iWindowHeight; + float const screenratio = static_cast( Global.iWindowWidth ) / Global.iWindowHeight; float const width = ( screenratio >= ( 4.f / 3.f ) ? - ( 4.f / 3.f ) * Global::iWindowHeight : - Global::iWindowWidth ); + ( 4.f / 3.f ) * Global.iWindowHeight : + Global.iWindowWidth ); float const heightratio = ( screenratio >= ( 4.f / 3.f ) ? - Global::iWindowHeight / 768.f : - Global::iWindowHeight / 768.f * screenratio / ( 4.f / 3.f ) ); + Global.iWindowHeight / 768.f : + Global.iWindowHeight / 768.f * screenratio / ( 4.f / 3.f ) ); float const height = 768.f * heightratio; /* - float const heightratio = Global::iWindowHeight / 768.0f; + float const heightratio = Global.iWindowHeight / 768.0f; float const height = 768.0f * heightratio; - float const width = Global::iWindowWidth * heightratio; + float const width = Global.iWindowWidth * heightratio; */ glColor4fv(&Color.x); glBegin( GL_TRIANGLE_STRIP ); - glMultiTexCoord2f( m_textureunit, 0.f, 1.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio ); - glMultiTexCoord2f( m_textureunit, 0.f, 0.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio ); - glMultiTexCoord2f( m_textureunit, 1.f, 1.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio ); - glMultiTexCoord2f( m_textureunit, 1.f, 0.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio ); + glMultiTexCoord2f( m_textureunit, 0.f, 1.f ); glVertex2f( 0.5f * ( Global.iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global.iWindowHeight - height ) + Coordinates.y * heightratio ); + glMultiTexCoord2f( m_textureunit, 0.f, 0.f ); glVertex2f( 0.5f * ( Global.iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global.iWindowHeight - height ) + Coordinates.w * heightratio ); + glMultiTexCoord2f( m_textureunit, 1.f, 1.f ); glVertex2f( 0.5f * ( Global.iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global.iWindowHeight - height ) + Coordinates.y * heightratio ); + glMultiTexCoord2f( m_textureunit, 1.f, 0.f ); glVertex2f( 0.5f * ( Global.iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global.iWindowHeight - height ) + Coordinates.w * heightratio ); glEnd(); } diff --git a/uitranscripts.cpp b/uitranscripts.cpp new file mode 100644 index 00000000..73797b2b --- /dev/null +++ b/uitranscripts.cpp @@ -0,0 +1,79 @@ + + +#include "stdafx.h" +#include "uitranscripts.h" + +#include "globals.h" +#include "parser.h" +#include "utilities.h" + +namespace ui { + +TTranscripts Transcripts; + +// dodanie linii do tabeli, (show) i (hide) w [s] od aktualnego czasu +void +TTranscripts::AddLine( std::string const &txt, float show, float hide, bool it ) { + + if( show == hide ) { return; } // komentarz jest ignorowany + + show = Global.fTimeAngleDeg + show / 240.0; // jeśli doba to 360, to 1s będzie równe 1/240 + hide = Global.fTimeAngleDeg + hide / 240.0; + + TTranscript transcript; + transcript.asText = txt; + transcript.fShow = show; + transcript.fHide = hide; + transcript.bItalic = it; + aLines.emplace_back( transcript ); + // set the next refresh time while at it + // TODO, TBD: sort the transcript lines? in theory, they should be coming arranged in the right order anyway + // short of cases with multiple sounds overleaping + fRefreshTime = aLines.front().fHide; +} + +// dodanie tekstów, długość dźwięku, czy istotne +void +TTranscripts::Add( std::string const &txt, bool backgorund ) { + + if( true == txt.empty() ) { return; } + + std::string asciitext{ txt }; win1250_to_ascii( asciitext ); // TODO: launch relevant conversion table based on language + cParser parser( asciitext ); + while( true == parser.getTokens( 3, false, "[]\n" ) ) { + + float begin, end; + std::string transcript; + parser + >> begin + >> end + >> transcript; + AddLine( transcript, 0.10 * begin, 0.12 * end, false ); + } + // try to handle malformed(?) cases with no show/hide times + std::string transcript; parser >> transcript; + while( false == transcript.empty() ) { + + // WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); + AddLine( transcript, 0.0, 0.12 * transcript.size(), false ); + transcript = ""; parser >> transcript; + } +} + +// usuwanie niepotrzebnych (nie częściej niż 10 razy na sekundę) +void +TTranscripts::Update() { + + if( Global.fTimeAngleDeg < fRefreshTime ) { return; } // nie czas jeszcze na zmiany + + while( ( false == aLines.empty() ) + && ( Global.fTimeAngleDeg >= aLines.front().fHide ) ) { + // remove expired lines + aLines.pop_front(); + } + // update next refresh time + if( false == aLines.empty() ) { fRefreshTime = aLines.front().fHide; } + else { fRefreshTime = 360.0f; } +} + +} // namespace ui diff --git a/uitranscripts.h b/uitranscripts.h new file mode 100644 index 00000000..56c27f08 --- /dev/null +++ b/uitranscripts.h @@ -0,0 +1,40 @@ + +#pragma once + +#include +#include + +namespace ui { + +// klasa obsługująca linijkę napisu do dźwięku +struct TTranscript { + + float fShow; // czas pokazania + float fHide; // czas ukrycia/usunięcia + std::string asText; // tekst gotowy do wyświetlenia (usunięte znaczniki czasu) + bool bItalic; // czy kursywa (dźwięk nieistotny dla prowadzącego) +}; + +// klasa obsługująca napisy do dźwięków +class TTranscripts { + +public: +// methods + void AddLine( std::string const &txt, float show, float hide, bool it ); + // dodanie tekstów, długość dźwięku, czy istotne + void Add( std::string const &txt, bool background = false ); + // usuwanie niepotrzebnych (ok. 10 razy na sekundę) + void Update(); + +// members + std::deque aLines; + +private: +// members + float fRefreshTime { 360 }; // wartośc zaporowa + +}; + +extern TTranscripts Transcripts; + +} // namespace ui \ No newline at end of file diff --git a/usefull.h b/usefull.h deleted file mode 100644 index 4f2594b3..00000000 --- a/usefull.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -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/. -*/ - -#pragma once - -#include "stdafx.h" - -#define sign(x) ((x) < 0 ? -1 : ((x) > 0 ? 1 : 0)) - -#define DegToRad(a) ((M_PI / 180.0) * (a)) //(a) w nawiasie, bo może być dodawaniem -#define RadToDeg(r) ((180.0 / M_PI) * (r)) - -#define asModelsPath std::string("models\\") -#define asSceneryPath std::string("scenery\\") -#define szSceneryPath "scenery\\" -#define szTexturePath "textures\\" -#define szSoundPath "sounds\\" - -#define MAKE_ID4(a,b,c,d) (((std::uint32_t)(d)<<24)|((std::uint32_t)(c)<<16)|((std::uint32_t)(b)<<8)|(std::uint32_t)(a)) - -template -void SafeDelete( Type_ &Pointer ) { - delete Pointer; - Pointer = nullptr; -} - -template -void SafeDeleteArray( Type_ &Pointer ) { - delete[] Pointer; - Pointer = nullptr; -} - -template -Type_ -clamp( Type_ const Value, Type_ const Min, Type_ const Max ) { - - Type_ value = Value; - if( value < Min ) { value = Min; } - if( value > Max ) { value = Max; } - return value; -} - -// keeps the provided value in specified range 0-Range, as if the range was circular buffer -template -Type_ -clamp_circular( Type_ Value, Type_ const Range = static_cast(360) ) { - - Value -= Range * (int)( Value / Range ); // clamp the range to 0-360 - if( Value < Type_(0) ) Value += Range; - - return Value; -} - -template -Type_ -interpolate( Type_ const &First, Type_ const &Second, float const Factor ) { - - return ( First * ( 1.0f - Factor ) ) + ( Second * Factor ); -} - -template -Type_ -interpolate( Type_ const &First, Type_ const &Second, double const Factor ) { - - return ( First * ( 1.0 - Factor ) ) + ( Second * Factor ); -} - -// tests whether provided points form a degenerate triangle -template -bool -degenerate( VecType_ const &Vertex1, VecType_ const &Vertex2, VecType_ const &Vertex3 ) { - - // degenerate( A, B, C, minarea ) = ( ( B - A ).cross( C - A ) ).lengthSquared() < ( 4.0f * minarea * minarea ); - return ( glm::length2( glm::cross( Vertex2 - Vertex1, Vertex3 - Vertex1 ) ) == 0.0 ); -} - -// calculates bounding box for provided set of points -template -void -bounding_box( VecType_ &Mincorner, VecType_ &Maxcorner, Iterator_ First, Iterator_ Last ) { - - Mincorner = VecType_( typename std::numeric_limits::max() ); - Maxcorner = VecType_( typename std::numeric_limits::lowest() ); - - std::for_each( - First, Last, - [&]( typename Iterator_::value_type &point ) { - Mincorner = glm::min( Mincorner, VecType_{ point } ); - Maxcorner = glm::max( Maxcorner, VecType_{ point } ); } ); -} - -// finds point on specified segment closest to specified point in 3d space. returns: point on segment as value in range 0-1 where 0 = start and 1 = end of the segment -template -typename VecType_::value_type -nearest_segment_point( VecType_ const &Segmentstart, VecType_ const &Segmentend, VecType_ const &Point ) { - - auto const v = Segmentend - Segmentstart; - auto const w = Point - Segmentstart; - - auto const c1 = glm::dot( w, v ); - if( c1 <= 0.0 ) { - return 0.0; - } - auto const c2 = glm::dot( v, v ); - if( c2 <= c1 ) { - return 1.0; - } - return c1 / c2; -} - -//--------------------------------------------------------------------------- diff --git a/utilities.cpp b/utilities.cpp new file mode 100644 index 00000000..d515fb43 --- /dev/null +++ b/utilities.cpp @@ -0,0 +1,320 @@ +/* +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/. +*/ +/* +MaSzyna EU07 - SPKS +Brakes. +Copyright (C) 2007-2014 Maciej Cierniak +*/ +#include "stdafx.h" + +#include +#include +#ifndef WIN32 +#include +#endif + +#ifdef WIN32 +#define stat _stat +#endif + +#include "utilities.h" +#include "globals.h" + +bool DebugModeFlag = false; +bool FreeFlyModeFlag = false; +bool EditorModeFlag = true; +bool DebugCameraFlag = false; + +double Max0R(double x1, double x2) +{ + if (x1 > x2) + return x1; + else + return x2; +} + +double Min0R(double x1, double x2) +{ + if (x1 < x2) + return x1; + else + return x2; +} + +// shitty replacement for Borland timestamp function +// TODO: replace with something sensible +std::string Now() { + + std::time_t timenow = std::time( nullptr ); + std::tm tm = *std::localtime( &timenow ); + std::stringstream converter; + converter << std::put_time( &tm, "%c" ); + return converter.str(); +} + +bool SetFlag( int &Flag, int const Value ) { + + if( Value > 0 ) { + if( false == TestFlag( Flag, Value ) ) { + Flag |= Value; + return true; // true, gdy było wcześniej 0 i zostało ustawione + } + } + else if( Value < 0 ) { + // Value jest ujemne, czyli zerowanie flagi + return ClearFlag( Flag, -Value ); + } + return false; +} + +bool ClearFlag( int &Flag, int const Value ) { + + if( true == TestFlag( Flag, Value ) ) { + Flag &= ~Value; + return true; + } + else { + return false; + } +} + +inline double Random(double a, double b) +{ + std::uniform_real_distribution<> dis(a, b); + return dis(Global.random_engine); +} + +bool FuzzyLogic(double Test, double Threshold, double Probability) +{ + if ((Test > Threshold) && (!DebugModeFlag)) + return + (Random() < Probability * Threshold * 1.0 / Test) /*im wiekszy Test tym wieksza szansa*/; + else + return false; +} + +bool FuzzyLogicAI(double Test, double Threshold, double Probability) +{ + if ((Test > Threshold)) + return + (Random() < Probability * Threshold * 1.0 / Test) /*im wiekszy Test tym wieksza szansa*/; + else + return false; +} + +std::string DUE(std::string s) /*Delete Before Equal sign*/ +{ + //DUE = Copy(s, Pos("=", s) + 1, length(s)); + return s.substr(s.find("=") + 1, s.length()); +} + +std::string DWE(std::string s) /*Delete After Equal sign*/ +{ + size_t ep = s.find("="); + if (ep != std::string::npos) + //DWE = Copy(s, 1, ep - 1); + return s.substr(0, ep); + else + return s; +} + +std::string ExchangeCharInString( std::string const &Source, char const From, char const To ) +{ + std::string replacement; replacement.reserve( Source.size() ); + std::for_each( + std::begin( Source ), std::end( Source ), + [&](char const idx) { + if( idx != From ) { replacement += idx; } + else { replacement += To; } } ); + + return replacement; +} + +std::vector &Split(const std::string &s, char delim, std::vector &elems) +{ // dzieli tekst na wektor tekstow + + std::stringstream ss(s); + std::string item; + while (std::getline(ss, item, delim)) + { + elems.push_back(item); + } + return elems; +} + +std::vector Split(const std::string &s, char delim) +{ // dzieli tekst na wektor tekstow + std::vector elems; + Split(s, delim, elems); + return elems; +} + +std::vector Split(const std::string &s) +{ // dzieli tekst na wektor tekstow po białych znakach + std::vector elems; + std::stringstream ss(s); + std::string item; + while (ss >> item) + { + elems.push_back(item); + } + return elems; +} + +std::string to_string(int _Val) +{ + std::ostringstream o; + o << _Val; + return o.str(); +}; + +std::string to_string(unsigned int _Val) +{ + std::ostringstream o; + o << _Val; + return o.str(); +}; + +std::string to_string(double _Val) +{ + std::ostringstream o; + o << _Val; + return o.str(); +}; + +std::string to_string(int _Val, int precision) +{ + std::ostringstream o; + o << std::fixed << std::setprecision(precision); + o << _Val; + return o.str(); +}; + +std::string to_string(double _Val, int precision) +{ + std::ostringstream o; + o << std::fixed << std::setprecision(precision); + o << _Val; + return o.str(); +}; + +std::string to_string(int _Val, int precision, int width) +{ + std::ostringstream o; + o.width(width); + o << std::fixed << std::setprecision(precision); + o << _Val; + return o.str(); +}; + +std::string to_string(double const Value, int const Precision, int const Width) +{ + std::ostringstream converter; + converter << std::setw( Width ) << std::fixed << std::setprecision(Precision) << Value; + return converter.str(); +}; + +std::string to_hex_str( int const Value, int const Width ) +{ + std::ostringstream converter; + converter << "0x" << std::uppercase << std::setfill( '0' ) << std::setw( Width ) << std::hex << Value; + return converter.str(); +}; + +int stol_def(const std::string &str, const int &DefaultValue) { + + int result { DefaultValue }; + std::stringstream converter; + converter << str; + converter >> result; + return result; +} + +std::string ToLower(std::string const &text) +{ + std::string lowercase( text ); + std::transform(text.begin(), text.end(), lowercase.begin(), ::tolower); + return lowercase; +} + +std::string ToUpper(std::string const &text) +{ + std::string uppercase( text ); + std::transform(text.begin(), text.end(), uppercase.begin(), ::toupper); + return uppercase; +} + +// replaces polish letters with basic ascii +void +win1250_to_ascii( std::string &Input ) { + + std::unordered_map charmap{ + { 165, 'A' }, { 198, 'C' }, { 202, 'E' }, { 163, 'L' }, { 209, 'N' }, { 211, 'O' }, { 140, 'S' }, { 143, 'Z' }, { 175, 'Z' }, + { 185, 'a' }, { 230, 'c' }, { 234, 'e' }, { 179, 'l' }, { 241, 'n' }, { 243, 'o' }, { 156, 's' }, { 159, 'z' }, { 191, 'z' } + }; + std::unordered_map::const_iterator lookup; + for( auto &input : Input ) { + if( ( lookup = charmap.find( input ) ) != charmap.end() ) + input = lookup->second; + } +} + +// Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów +char bezogonkowo[] = "E?,?\"_++?%Sstzz" + " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" + "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" + "raaaalccceeeeiiddnnoooo-ruuuuyt?"; + +std::string Bezogonkow(std::string str, bool _) +{ // wycięcie liter z ogonkami, bo OpenGL nie umie wyświetlić + for (unsigned int i = 1; i < str.length(); ++i) + if (str[i] & 0x80) + str[i] = bezogonkowo[str[i] & 0x7F]; + else if (str[i] < ' ') // znaki sterujące nie są obsługiwane + str[i] = ' '; + else if (_) + if (str[i] == '_') // nazwy stacji nie mogą zawierać spacji + str[i] = ' '; // więc trzeba wyświetlać inaczej + return str; +}; + +template <> +bool +extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) { + + auto value = extract_value( Key, Input ); + if( false == value.empty() ) { + // set the specified variable to retrieved value + Variable = ( ToLower( value ) == "yes" ); + return true; // located the variable + } + else { + // set the variable to provided default value + if( false == Default.empty() ) { + Variable = ( ToLower( Default ) == "yes" ); + } + return false; // couldn't locate the variable in provided input + } +} + +bool +FileExists( std::string const &Filename ) { + + std::ifstream file( Filename ); + return( true == file.is_open() ); +} + +// returns time of last modification for specified file +std::time_t +last_modified( std::string const &Filename ) { + + struct stat filestat; + if( ::stat( Filename.c_str(), &filestat ) == 0 ) { return filestat.st_mtime; } + else { return 0; } +} diff --git a/utilities.h b/utilities.h new file mode 100644 index 00000000..a9501fca --- /dev/null +++ b/utilities.h @@ -0,0 +1,286 @@ +/* +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/. +*/ + +#pragma once + +#include "stdafx.h" + +#include +#include +#include +#include +#include + +/*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/ +/*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/ + +#define sign(x) ((x) < 0 ? -1 : ((x) > 0 ? 1 : 0)) + +#define DegToRad(a) ((M_PI / 180.0) * (a)) //(a) w nawiasie, bo może być dodawaniem +#define RadToDeg(r) ((180.0 / M_PI) * (r)) + +#define asModelsPath std::string("models\\") +#define asSceneryPath std::string("scenery\\") +#define szSceneryPath "scenery\\" +#define szTexturePath "textures\\" +#define szSoundPath "sounds\\" + +#define MAKE_ID4(a,b,c,d) (((std::uint32_t)(d)<<24)|((std::uint32_t)(c)<<16)|((std::uint32_t)(b)<<8)|(std::uint32_t)(a)) + +extern bool DebugModeFlag; +extern bool FreeFlyModeFlag; +extern bool EditorModeFlag; +extern bool DebugCameraFlag; + +/*funkcje matematyczne*/ +double Max0R(double x1, double x2); +double Min0R(double x1, double x2); + +inline double Sign(double x) +{ + return x >= 0 ? 1.0 : -1.0; +} + +inline long Round(double const f) +{ + return (long)(f + 0.5); + //return lround(f); +} + +double Random(double a, double b); + +inline double Random() +{ + return Random(0.0,1.0); +} + +inline double Random(double b) +{ + return Random(0.0, b); +} + +inline double BorlandTime() +{ + auto timesinceepoch = std::time( nullptr ); + return timesinceepoch / (24.0 * 60 * 60); +/* + // std alternative + auto timesinceepoch = std::chrono::system_clock::now().time_since_epoch(); + return std::chrono::duration_cast( timesinceepoch ).count() / (24.0 * 60 * 60); +*/ +} + +std::string Now(); + +/*funkcje logiczne*/ +inline bool TestFlag( int const Flag, int const Value ) { return ( ( Flag & Value ) == Value ); } +bool SetFlag( int &Flag, int const Value); +bool ClearFlag(int &Flag, int const Value); + +bool FuzzyLogic(double Test, double Threshold, double Probability); +/*jesli Test>Threshold to losowanie*/ +bool FuzzyLogicAI(double Test, double Threshold, double Probability); +/*to samo ale zawsze niezaleznie od DebugFlag*/ + +/*operacje na stringach*/ +std::string DUE(std::string s); /*Delete Until Equal sign*/ +std::string DWE(std::string s); /*Delete While Equal sign*/ +std::string ExchangeCharInString( std::string const &Source, char const From, char const To ); // zamienia jeden znak na drugi +std::vector &Split(const std::string &s, char delim, std::vector &elems); +std::vector Split(const std::string &s, char delim); +//std::vector Split(const std::string &s); + +std::string to_string(int _Val); +std::string to_string(unsigned int _Val); +std::string to_string(int _Val, int precision); +std::string to_string(int _Val, int precision, int width); +std::string to_string(double _Val); +std::string to_string(double _Val, int precision); +std::string to_string(double _Val, int precision, int width); +std::string to_hex_str( int const _Val, int const width = 4 ); + +inline std::string to_string(bool _Val) { + + return _Val == true ? "true" : "false"; +} + +template +std::string to_string( glm::tvec3 const &Value ) { + return to_string( Value.x, 2 ) + ", " + to_string( Value.y, 2 ) + ", " + to_string( Value.z, 2 ); +} + +template +std::string to_string( glm::tvec4 const &Value, int const Width = 2 ) { + return to_string( Value.x, Width ) + ", " + to_string( Value.y, Width ) + ", " + to_string( Value.z, Width ) + ", " + to_string( Value.w, Width ); +} + +int stol_def(const std::string & str, const int & DefaultValue); + +std::string ToLower(std::string const &text); +std::string ToUpper(std::string const &text); + +// replaces polish letters with basic ascii +void win1250_to_ascii( std::string &Input ); +// TODO: unify with win1250_to_ascii() +std::string Bezogonkow( std::string str, bool _ = false ); + +inline +std::string +extract_value( std::string const &Key, std::string const &Input ) { + // NOTE, HACK: the leading space allows to uniformly look for " variable=" substring + std::string const input { " " + Input }; + std::string value; + auto lookup = input.find( " " + Key + "=" ); + if( lookup != std::string::npos ) { + value = input.substr( input.find_first_not_of( ' ', lookup + Key.size() + 2 ) ); + lookup = value.find( ' ' ); + if( lookup != std::string::npos ) { + // trim everything past the value + value.erase( lookup ); + } + } + return value; +} + +template +bool +extract_value( Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) { + + auto value = extract_value( Key, Input ); + if( false == value.empty() ) { + // set the specified variable to retrieved value + std::stringstream converter; + converter << value; + converter >> Variable; + return true; // located the variable + } + else { + // set the variable to provided default value + if( false == Default.empty() ) { + std::stringstream converter; + converter << Default; + converter >> Variable; + } + return false; // couldn't locate the variable in provided input + } +} + +template <> +bool +extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default ); + +bool FileExists( std::string const &Filename ); + +// returns time of last modification for specified file +std::time_t last_modified( std::string const &Filename ); + +template +void SafeDelete( Type_ &Pointer ) { + delete Pointer; + Pointer = nullptr; +} + +template +void SafeDeleteArray( Type_ &Pointer ) { + delete[] Pointer; + Pointer = nullptr; +} + +template +Type_ +clamp( Type_ const Value, Type_ const Min, Type_ const Max ) { + + Type_ value = Value; + if( value < Min ) { value = Min; } + if( value > Max ) { value = Max; } + return value; +} + +// keeps the provided value in specified range 0-Range, as if the range was circular buffer +template +Type_ +clamp_circular( Type_ Value, Type_ const Range = static_cast(360) ) { + + Value -= Range * (int)( Value / Range ); // clamp the range to 0-360 + if( Value < Type_(0) ) Value += Range; + + return Value; +} + +template +Type_ +min_speed( Type_ const Left, Type_ const Right ) { + + return std::min( + ( Left != -1 ? + Left : + std::numeric_limits::max() ), + ( Right != -1 ? + Right : + std::numeric_limits::max() ) ); +} + +template +Type_ +interpolate( Type_ const &First, Type_ const &Second, float const Factor ) { + + return ( First * ( 1.0f - Factor ) ) + ( Second * Factor ); +} + +template +Type_ +interpolate( Type_ const &First, Type_ const &Second, double const Factor ) { + + return ( First * ( 1.0 - Factor ) ) + ( Second * Factor ); +} + +// tests whether provided points form a degenerate triangle +template +bool +degenerate( VecType_ const &Vertex1, VecType_ const &Vertex2, VecType_ const &Vertex3 ) { + + // degenerate( A, B, C, minarea ) = ( ( B - A ).cross( C - A ) ).lengthSquared() < ( 4.0f * minarea * minarea ); + return ( glm::length2( glm::cross( Vertex2 - Vertex1, Vertex3 - Vertex1 ) ) == 0.0 ); +} + +// calculates bounding box for provided set of points +template +void +bounding_box( VecType_ &Mincorner, VecType_ &Maxcorner, Iterator_ First, Iterator_ Last ) { + + Mincorner = VecType_( typename std::numeric_limits::max() ); + Maxcorner = VecType_( typename std::numeric_limits::lowest() ); + + std::for_each( + First, Last, + [&]( typename Iterator_::value_type &point ) { + Mincorner = glm::min( Mincorner, VecType_{ point } ); + Maxcorner = glm::max( Maxcorner, VecType_{ point } ); } ); +} + +// finds point on specified segment closest to specified point in 3d space. returns: point on segment as value in range 0-1 where 0 = start and 1 = end of the segment +template +typename VecType_::value_type +nearest_segment_point( VecType_ const &Segmentstart, VecType_ const &Segmentend, VecType_ const &Point ) { + + auto const v = Segmentend - Segmentstart; + auto const w = Point - Segmentstart; + + auto const c1 = glm::dot( w, v ); + if( c1 <= 0.0 ) { + return 0.0; + } + auto const c2 = glm::dot( v, v ); + if( c2 <= c1 ) { + return 1.0; + } + return c1 / c2; +} + +//--------------------------------------------------------------------------- diff --git a/vertex.h b/vertex.h index 0dcfbbb9..8ce99afa 100644 --- a/vertex.h +++ b/vertex.h @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include -#include "usefull.h" +#include "utilities.h" // geometry vertex with double precision position struct world_vertex { diff --git a/windows.cpp b/windows.cpp index 28b46abc..5d9cef25 100644 --- a/windows.cpp +++ b/windows.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" #include "World.h" -#include "usefull.h" +#include "utilities.h" #pragma warning (disable: 4091) #include