Project
Loading...
Searching...
No Matches
GPUDisplayFrontend.h
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
14
15#ifndef GPUDISPLAYFRONTEND_H
16#define GPUDISPLAYFRONTEND_H
17
18#include "GPUCommonDef.h"
19#include "GPUDisplayInterface.h"
21#include <atomic>
22#include <memory>
23#include <chrono>
24#include <mutex>
25#include <thread>
26#include <condition_variable>
27#include <functional>
28#include <string>
29#include <utility>
30#include <vector>
31
32namespace o2::gpu
33{
34struct GPUDisplayGUIUpdate;
35class GPUReconstruction;
36class GPUDisplay;
37class GPUDisplayBackend;
38class GPUDisplayGUIWrapper;
39class GPUDisplayConsole;
40struct GPUDisplayGUIChannel;
41
43{
44 friend class GPUDisplay;
45
46 public:
48 ~GPUDisplayFrontend() override;
49
59
60 // Compile time minimum version checked in display/CMakeLists.txt (OpenGL 4.6 headers for SPIR-V shaders), keep in sync!
61 static constexpr int32_t GL_MIN_VERSION_MAJOR = 4;
62 static constexpr int32_t GL_MIN_VERSION_MINOR = 6;
63
64 int32_t StartDisplay(); // Start the display: spawns the frontend thread (FrontendThreadWrapper, calls InitDisplay), returns after both threads are initialized
65 void StopDisplay() override; // Stop the display. Display thread should call ExitDisplay. Functions waits for display thread to terminate
66 virtual void SwitchFullscreen(bool set) = 0; // Toggle full-screen mode
67 virtual void ToggleMaximized(bool set) = 0; // Maximize window
68 virtual void SetVSync(bool enable) = 0; // Enable / disable vsync
69 virtual bool canSetVSync() { return false; } // OpenGL: swap interval can be set
71 static GPUDisplayFrontend* getFrontend(const char* type);
72 virtual void getSize(int32_t& width, int32_t& height) { width = height = 0; }
73 virtual float getRefreshRate() { return 0.f; } // Refresh rate of the display the window is on in Hz, 0 = unknown
74 virtual float getDisplayScale() const { return 1.f; } // HiDPI scale factor: physical pixels per logical pixel, text positions and sizes are scaled by it
75 virtual int32_t getVulkanSurface(void* instance, void* surface) { return 1; }
76 virtual uint32_t getReqVulkanExtensions(const char**& p) { return 0; };
77
78 int32_t getDisplayControl() const override;
79 void setDisplayControl(int32_t v) override;
80 void sendExternalGUIKey(int32_t v, uint32_t translationMode = 0, uint64_t extendedKey = 0) override;
81
83 const char* frontendName() const override { return mFrontendName; }
84
86 void stopGUI();
87 bool isGUIRunning();
88
89 protected:
90 virtual int32_t FrontendMain() = 0;
91 virtual void StopDisplayA();
92 void FrontendThreadWrapper(); // Runs FrontendMain in mFrontendThread
93 void waitForFPSLimit(); // Sleep until the next frame is due according to fpsRate (only in FPS_LIMIT_RATE mode, see GPUDisplayBackend::fpsLimitMode), or until an external config update is signalled
94 void signalConfigUpdate(); // Signal a config update from an external source (console keys, Qt GUI), wakes up waitForFPSLimit
95
96 static constexpr int32_t INIT_WIDTH = 1024, INIT_HEIGHT = 768; // Initial window size, before maximizing
97 static constexpr int32_t MIN_WIDTH = 200, MIN_HEIGHT = 150; // Minimum window size
98 static constexpr const char* DISPLAY_WINDOW_NAME = "GPU CA Standalone Event Display"; // Title of event display set by backend
99 static constexpr uint32_t N_SPECIAL_KEYS = 32;
100 static constexpr uint32_t SPECIAL_KEYS_SHIFTED = 255;
101 static constexpr uint32_t N_TOTAL_KEYS = 256 + N_SPECIAL_KEYS;
102
104 std::vector<int32_t> mExternalGUIKeys; // Keys sent by external entity (usually console), may be ignored by backend.
106 std::condition_variable mConfigUpdateCV; // Notified by signalConfigUpdate
107 bool mConfigUpdatePending = false; // Protected by mConfigUpdateMutex, set by signalConfigUpdate, cleared by HandleExternalGUISignals
108 std::mutex mExitStateMutex;
109 std::condition_variable mDisplayStoppedCV; // Notified with mExitStateMutex held when the frontend sets mDisplayRunning to false, StopDisplay waits for it
110 std::condition_variable mInitCV; // With mExitStateMutex: InitDisplay (frontend thread) and StartDisplay (main thread) wait for each other at their end
111 std::thread mFrontendThread; // Started by StartDisplay, joined by StopDisplay
112 bool mStartDisplayDone = false; // Protected by mExitStateMutex
113 bool mStartupScriptDone = false; // GPUSettingsDisplay::runScript runs after the first (suspended) frame
114 std::array<uint8_t, KEY_MAP_MAX> mKeyDownMap = {};
115
116 // Keyboard / Mouse actions
117 bool mMouseDn = false; // Mouse button down
118 bool mMouseDnR = false; // Right mouse button down
119 bool mMouseDnM = false; // Middle mouse button down, as left + right
120 float mMouseDnX, mMouseDnY; // X/Y position where mouse button was pressed
121 float mMouseMvX, mMouseMvY; // Current mouse pointer position
122 int32_t mMouseWheel = 0; // Incremental value of mouse wheel, ca +/- 100 per wheel tick
123 bool mKeys[256] = {false}; // Array of mKeys currently pressed (not while the console is shown)
126
127 std::chrono::steady_clock::time_point mNextFrameTime;
128
129 GPUDisplay* mDisplay = nullptr; // Ptr to display, not owning, set by display when it connects to backend
130 GPUDisplayBackend* mBackend = nullptr; // Ptr to backend, not owning
131
133 const char* mFrontendName = nullptr;
134 std::atomic<bool> mDisplayRunning = false; // Set at the end of a successful InitDisplay, StopDisplay waits for it to become false again
135
136 std::unique_ptr<GPUDisplayGUIChannel> mGUIChannel; // Must outlive mGUI
137 std::unique_ptr<GPUDisplayGUIWrapper> mGUI;
138
139 int32_t HandleUpdatesAndDrawGLScene(bool suspended = false); // Handle external GUI signals and config changes, then draw the scene (suspended: only update, no drawing, e.g. for a hidden window)
140
141 void HandleKey(uint8_t key); // Callback for handling key presses
142 bool consoleShown() const; // Key presses go to the console, frontends do not set mKeys
143 bool keyMapDown(uint32_t id) const; // Key of the KEY_MAP_* mapping held, never for unbound ones
144 void HandleExternalGUISignals(); // Callback to handle signals from external GUIs
145 bool processKeyLambda(uint32_t key); // Process key lambda callback
146 uint32_t shiftedKey(uint32_t key) const; // Special keys with SHIFT held at code + SPECIAL_KEYS_SHIFTED, as in configKeys
147 void showConfigInfo(uint32_t index); // Info for a changed option (index in the config RTTI): its info callback, or "struct.option changed to value"
148 void ResizeScene(int32_t width, int32_t height); // Callback when GL window is resized
149 int32_t InitDisplay(bool initFailure = false); // Callback to initialize the GL Display (to be called in StartDisplay)
150 void ExitDisplay(); // Callback to clean up the GL Display
152 bool vsyncEnabled() const; // VSync setting (drawQualityVSync)
153 void setWindowState(bool fullScreen, bool maximized); // Sync the settings if the window manager changed the window state
154 void focusLost(); // Release all keys and mouse buttons when the window loses focus, since the release events go to another window
155 void applyInitialWindowState(); // Switch to fullscreen / maximize at startup according to the settings
156 void requestFullScreen(bool set); // Call SwitchFullscreen / ToggleMaximized only if the state differs from the last requested or reported (setWindowState) one
157 void requestMaximized(bool set);
158
159 private:
161 struct configRTTIExt;
162 std::unique_ptr<GPUDisplayConfiguration, void (*)(GPUDisplayConfiguration*)> mConfiguration{nullptr, nullptr}; // Deleter set in GPUDisplayFrontendConfig.cxx, the only place where GPUDisplayConfiguration is defined
163
164 void HandleExternalGUIKeys();
165 static int32_t translateExternalKey(uint32_t translationMode, uint64_t extendedKey); // Key code of an encoded key of sendExternalGUIKey (+ SPECIAL_KEYS_SHIFTED with SHIFT), -1 if unknown
166 void buildConsoleCommands(); // Fills mConsole->mConsoleCommands, GPUDisplayFrontendConfigConsole.inc (commands need the config RTTI)
167 std::unique_ptr<GPUDisplayConsole> mConsole;
168 bool mWindowFullScreen = false, mWindowMaximized = false; // Window state last requested or reported by the window system
169 template <typename... Args>
170 void add_key_binding(Args&&... args); // KEY_LAMBDA(key, ...) entries, the help text, and optionally the keys to show in the help text, only used in GPUDisplayFrontendConfig.cxx
171 template <typename... Args>
172 void add_gui_binding(Args&&... args); // GUI_LAMBDA(name, ...) entries shown in one frame of the Qt GUI, and optionally its description and a flag to place the elements horizontally (default vertically), only used in GPUDisplayFrontendConfig.cxx
173 void setGUILayout(GPUDisplayGUIChannel& channel) const; // Copy the GUI elements of the add_gui_binding calls to the channel
174 void applyGUIValues(const GPUDisplayGUIUpdate& update); // Call the setter of the GUI elements changed in the GUI (element id, value), and show the info of their options
175 void listConfig();
176 const std::vector<std::string>& getHelpText(); // Help text of all key bindings, one line per binding, rebuilt after key bindings changed
177 void listKeys(const std::function<void(const std::string&)>& print); // Bound keys with action / key down mapping and option, then unbound actions and mappings, then the key down mappings with their keys, one line per call
178};
179} // namespace o2::gpu
180
181#endif
void print() const
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events Show standalone event Run event generator maximum time bin of continuous for triggered for automatic continuous for automatic continuous triggered uint64_t
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder int32_t
const Acts::Surface * surface
StringRef key
std::unique_ptr< GPUDisplayGUIWrapper > mGUI
virtual uint32_t getReqVulkanExtensions(const char **&p)
virtual void getSize(int32_t &width, int32_t &height)
int32_t getDisplayControl() const override
static constexpr uint32_t N_SPECIAL_KEYS
std::unique_ptr< GPUDisplayGUIChannel > mGUIChannel
virtual int32_t FrontendMain()=0
void setDisplayControl(int32_t v) override
virtual void ToggleMaximized(bool set)=0
static constexpr uint32_t SPECIAL_KEYS_SHIFTED
uint32_t shiftedKey(uint32_t key) const
int32_t HandleUpdatesAndDrawGLScene(bool suspended=false)
static GPUDisplayFrontend * getFrontend(const char *type)
void ResizeScene(int32_t width, int32_t height)
std::condition_variable mDisplayStoppedCV
static constexpr const char * DISPLAY_WINDOW_NAME
frontendTypes frontendType() const
static constexpr int32_t INIT_WIDTH
static constexpr int32_t GL_MIN_VERSION_MAJOR
void setWindowState(bool fullScreen, bool maximized)
const char * frontendName() const override
std::vector< int32_t > mExternalGUIKeys
void sendExternalGUIKey(int32_t v, uint32_t translationMode=0, uint64_t extendedKey=0) override
virtual int32_t getVulkanSurface(void *instance, void *surface)
static constexpr int32_t GL_MIN_VERSION_MINOR
bool keyMapDown(uint32_t id) const
int32_t InitDisplay(bool initFailure=false)
std::array< uint8_t, KEY_MAP_MAX > mKeyDownMap
virtual void SetVSync(bool enable)=0
std::condition_variable mConfigUpdateCV
static constexpr int32_t MIN_WIDTH
static constexpr int32_t INIT_HEIGHT
std::chrono::steady_clock::time_point mNextFrameTime
virtual float getDisplayScale() const
static constexpr uint32_t N_TOTAL_KEYS
virtual void SwitchFullscreen(bool set)=0
static constexpr int32_t MIN_HEIGHT
std::atomic< bool > mDisplayRunning
std::condition_variable mInitCV
const GLdouble * v
Definition glcorearb.h:832
GLint GLsizei GLsizei height
Definition glcorearb.h:270
GLint GLsizei width
Definition glcorearb.h:270
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)