Vesper 0.5.1
Vesper is short form for the Latin word for "Bat", as Vesper is designed to be small, lightweight, and easily handle things like particles and flocking behaviors in accordance with the nature of bats. \n It is meant to be a particle simulation, VFX editor, and CAN be used secondarily as a small game engine.
GitHub | Vesper Updates | Creator
Loading...
Searching...
No Matches
Instrumentor.h
Go to the documentation of this file.
1
2/// @file Instrumentor.h
3/// @author TheCherno
4/// @author Damon S. Green II
5/// @brief Provides instrumentation and profiling utilities.
6
7//Copyright © TheCherno
8//Modifications Copyright © 2025 Damon S.Green II(nomad_ii_damon)
9//
10//Licensed under the Apache License, Version 2.0 (the "License");
11//you may not use this file except in compliance with the License.
12//You may obtain a copy of the License at
13//
14//[Apache](http://www.apache.org/licenses/LICENSE-2.0)
15
16#pragma once
17
18#include "Vesper/Core/Log.h"
19
20#include <algorithm>
21#include <chrono>
22#include <fstream>
23#include <iomanip>
24#include <string>
25#include <thread>
26#include <mutex>
27#include <sstream>
28
29namespace Vesper {
30
31 using FloatingPointMicroseconds = std::chrono::duration<double, std::micro>;
32
33
34 struct ProfileResult
35 {
36 std::string Name;
37 long long Start, End;
38 uint32_t ThreadID;
39 };
40
41 struct InstrumentationSession
42 {
43 std::string Name;
44 };
45
46 class Instrumentor
47 {
48 private:
49 InstrumentationSession* m_CurrentSession;
50 std::ofstream m_OutputStream;
51 std::mutex m_Mutex;
52 public:
53 Instrumentor()
54 : m_CurrentSession(nullptr)
55 {
56 }
57
58 void BeginSession(const std::string& name, const std::string& filepath = "results.json")
59 {
60 std::lock_guard lock(m_Mutex);
61 if (m_CurrentSession) {
62 // If there is already a current session, end it and start new one
63 if (Log::GetCoreLogger())
64 {
65 VZ_CORE_ERROR("Instrumentor::BeginSession('{0}') when session '{1}' already open.", name, m_CurrentSession->Name);
66 }
67 InternalEndSession();
68 }
69 m_OutputStream.open(filepath);
70 if (m_OutputStream.is_open()) {
71 m_CurrentSession = new InstrumentationSession{ name };
72 WriteHeader();
73 }
74 else {
75 if (Log::GetCoreLogger())
76 {
77 VZ_CORE_ERROR("Instrumentor could not open results file '{0}'.", filepath);
78 }
79 }
80 WriteHeader();
81 m_CurrentSession = new InstrumentationSession{ name };
82 }
83
84 void EndSession()
85 {
86 std::lock_guard lock(m_Mutex);
87 InternalEndSession();
88 }
89
90 void WriteProfile(const ProfileResult& result)
91 {
92 m_OutputStream << ",";
93
94 std::string name = result.Name;
95 std::replace(name.begin(), name.end(), '"', '\'');
96
97 m_OutputStream << "{";
98 m_OutputStream << "\"cat\":\"function\",";
99 m_OutputStream << "\"dur\":" << (result.End - result.Start) << ',';
100 m_OutputStream << "\"name\":\"" << name << "\",";
101 m_OutputStream << "\"ph\":\"X\",";
102 m_OutputStream << "\"pid\":0,";
103 m_OutputStream << "\"tid\":" << result.ThreadID << ",";
104 m_OutputStream << "\"ts\":" << result.Start;
105 m_OutputStream << "}";
106
107 std::lock_guard lock(m_Mutex);
108 if (m_CurrentSession)
109 {
110 //m_OutputStream << json.str();
111 m_OutputStream.flush();
112 }
113 }
114
115 void WriteHeader()
116 {
117 m_OutputStream << "{\"otherData\": {},\"traceEvents\":[";
118 m_OutputStream.flush();
119 }
120
121 void WriteFooter()
122 {
123 m_OutputStream << "]}";
124 m_OutputStream.flush();
125 }
126
127 void InternalEndSession()
128 {
129 if (m_CurrentSession)
130 {
131 WriteFooter();
132 m_OutputStream.close();
133 delete m_CurrentSession;
134 m_CurrentSession = nullptr;
135 }
136 }
137
138 static Instrumentor& Get()
139 {
140 static Instrumentor instance;
141 return instance;
142 }
143 };
144
145 class InstrumentationTimer
146 {
147 public:
148 InstrumentationTimer(const char* name)
149 : m_Name(name), m_Stopped(false)
150 {
151 m_StartTimepoint = std::chrono::high_resolution_clock::now();
152 }
153
154 ~InstrumentationTimer()
155 {
156 if (!m_Stopped)
157 Stop();
158 }
159
160 void Stop()
161 {
162 auto endTimepoint = std::chrono::high_resolution_clock::now();
163
164 long long start = std::chrono::time_point_cast<std::chrono::microseconds>(m_StartTimepoint).time_since_epoch().count();
165 long long end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimepoint).time_since_epoch().count();
166
167 uint32_t threadID = std::hash<std::thread::id>{}(std::this_thread::get_id());
168 Instrumentor::Get().WriteProfile({ m_Name, start, end, threadID });
169
170 m_Stopped = true;
171 }
172 private:
173 const char* m_Name;
174 std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTimepoint;
175 bool m_Stopped;
176 };
177
178
179}
180
181namespace InstrumentorUtils {
182
183 template <size_t N>
184 struct ChangeResult
185 {
186 char Data[N];
187 };
188
189 template <size_t N, size_t K>
190 constexpr auto CleanupOutputString(const char(&expr)[N], const char(&remove)[K])
191 {
192 ChangeResult<N> result = {};
193
194 size_t srcIndex = 0;
195 size_t dstIndex = 0;
196 while (srcIndex < N)
197 {
198 size_t matchIndex = 0;
199 while (matchIndex < K - 1 && srcIndex + matchIndex < N - 1 && expr[srcIndex + matchIndex] == remove[matchIndex])
200 matchIndex++;
201 if (matchIndex == K - 1)
202 srcIndex += matchIndex;
203 result.Data[dstIndex++] = expr[srcIndex] == '"' ? '\'' : expr[srcIndex];
204 srcIndex++;
205 }
206 return result;
207 }
208}
209
210
211#define VZ_PROFILE 1
212#if VZ_PROFILE
213 // Resolve which function signature macro will be used. Note that this only
214 // is resolved when the (pre)compiler starts, so the syntax highlighting
215 // could mark the wrong one in your editor!
216 #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) || defined(__ghs__)
217 #define VZ_FUNC_SIG __PRETTY_FUNCTION__
218 #elif defined(__DMC__) && (__DMC__ >= 0x810)
219 #define VZ_FUNC_SIG __PRETTY_FUNCTION__
220 #elif (defined(__FUNCSIG__) || (_MSC_VER))
221 #define VZ_FUNC_SIG __FUNCSIG__
222 #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500))
223 #define VZ_FUNC_SIG __FUNCTION__
224 #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550)
225 #define VZ_FUNC_SIG __FUNC__
226 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)
227 #define VZ_FUNC_SIG __func__
228 #elif defined(__cplusplus) && (__cplusplus >= 201103)
229 #define VZ_FUNC_SIG __func__
230 #else
231 #define VZ_FUNC_SIG "VZ_FUNC_SIG unknown!"
232 #endif
233
234 #define VZ_PROFILE_BEGIN_SESSION(name, filepath) ::Vesper::Instrumentor::Get().BeginSession(name, filepath)
235 #define VZ_PROFILE_END_SESSION() ::Vesper::Instrumentor::Get().EndSession()
236 #define VZ_PROFILE_SCOPE_LINE2(name, line) constexpr auto fixedName##line = InstrumentorUtils::CleanupOutputString(name, "__cdecl ");
237 ::Vesper::InstrumentationTimer timer##line(fixedName##line.Data)
238 #define VZ_PROFILE_SCOPE_LINE(name, line) VZ_PROFILE_SCOPE_LINE2(name, line)
239 #define VZ_PROFILE_SCOPE(name) VZ_PROFILE_SCOPE_LINE(name, __LINE__)
240 #define VZ_PROFILE_FUNCTION() VZ_PROFILE_SCOPE(VZ_FUNC_SIG)
241#else
242 #define VZ_PROFILE_BEGIN_SESSION(name, filepath)
243 #define VZ_PROFILE_END_SESSION()
244 #define VZ_PROFILE_FUNCTION()
245 #define VZ_PROFILE_SCOPE(name)
246#endif
#define VZ_CORE_ASSERT(x,...)
Definition Asserts.h:20
#define VZ_BIND_EVENT_FN(fn)
Binds a member function as an event handler.
Definition Defines_Macros.h:17
static const uint32_t s_MapHeight
Definition EditorLayer.cpp:13
static const char * s_MapTiles
Definition EditorLayer.cpp:14
static const uint32_t s_MapWidth
Definition EditorLayer.cpp:12
#define VZ_PROFILE
Definition Instrumentor.h:211
#define VZ_FUNC_SIG
Definition Instrumentor.h:231
#define VZ_PROFILE_SCOPE_LINE2(name, line)
Definition Instrumentor.h:236
#define VZ_PROFILE_FUNCTION()
Definition Instrumentor.h:240
#define VZ_PROFILE_SCOPE(name)
Definition Instrumentor.h:239
#define VZ_PROFILE_SCOPE_LINE(name, line)
Definition Instrumentor.h:238
#define VZ_CORE_INFO(...)
info: general information about application flow
Definition Log.h:37
#define VZ_CORE_ERROR(...)
error: indicates an error that has occurred
Definition Log.h:41
The core application class that manages the main loop, window, layers, and event handling.
Definition Application.h:35
static Application * s_Instance
Definition Application.h:92
void OnEvent(Event &e)
Handles incoming events and dispatches them to the appropriate handlers.
Definition Application.cpp:60
float m_LastFrameTime
Time of the last frame, used for calculating timestep.
Definition Application.h:89
bool OnWindowResize(WindowResizeEvent &e)
Event handler for window resize events.
Definition Application.cpp:118
static Application & Get()
Retrieves the singleton instance of the Application.
Definition Application.h:67
ImGuiLayer * m_ImGuiLayer
ImGui layer for rendering GUI elements.
Definition Application.h:81
bool m_Running
Flag indicating whether the application is running.
Definition Application.h:83
bool OnWindowClose(WindowCloseEvent &e)
Event handler for window close events.
Definition Application.cpp:111
ImGuiLayer * GetImGuiLayer()
Retrieves the ImGui layer.
Definition Application.h:64
void Run()
Starts the main application loop.
Definition Application.cpp:77
void PushLayer(Layer *layer)
Adds a layer to the application layer stack.
Definition Application.cpp:41
Application(const std::string &name="")
Constructs the Application with the given name.
Definition Application.cpp:17
LayerStack m_LayerStack
Stack of layers managed by the application.
Definition Application.h:87
void PushOverlay(Layer *overlay)
Adds an overlay layer to the application layer stack.
Definition Application.cpp:48
virtual ~Application()
Definition Application.cpp:37
Scope< Window > m_Window
Scoped pointer to the applications underlying window.
Definition Application.h:79
bool m_Minimized
Flag indicating whether the application is minimized.
Definition Application.h:85
void Close()
Closes the application.
Definition Application.cpp:55
Window & GetWindow()
Retrieves the application window.
Definition Application.h:70
Definition EditorCamera.h:13
Definition EditorLayer.h:14
glm::vec4 m_SpecialQuadColor
Definition EditorLayer.h:98
bool m_ViewportFocused
Definition EditorLayer.h:44
float m_RotationSnap
Definition EditorLayer.h:51
std::unordered_map< char, Ref< SubTexture2D > > s_TextureMap
Definition EditorLayer.h:101
Ref< Shader > m_FlatColorShader
Definition EditorLayer.h:60
void OpenScene()
Definition EditorLayer.cpp:728
glm::vec4 m_TextureTintColor1
Definition EditorLayer.h:94
float lastFrameTime
Definition EditorLayer.h:55
ParticleProps m_ParticleProps
Definition EditorLayer.h:87
glm::vec4 m_ClearColor
Definition EditorLayer.h:97
SceneState
Definition EditorLayer.h:39
@ Simulate
Definition EditorLayer.h:40
@ Edit
Definition EditorLayer.h:40
@ Play
Definition EditorLayer.h:40
bool scene3
Definition EditorLayer.h:90
Ref< SubTexture2D > m_SubTextureSmoke
Definition EditorLayer.h:71
Ref< Texture2D > m_SpriteSheetCursedLands
Definition EditorLayer.h:68
int m_GizmoType
Definition EditorLayer.h:50
bool scene4
Definition EditorLayer.h:90
ParticleSystem m_ParticleSystem
Definition EditorLayer.h:86
EditorLayer()
Definition EditorLayer.cpp:37
EditorCamera m_EditorCamera
Definition EditorLayer.h:79
Ref< Texture2D > m_SpriteSheetCrystals
Definition EditorLayer.h:66
float m_ScaleSnap
Definition EditorLayer.h:51
void NewScene()
Definition EditorLayer.cpp:721
float m_TranslationSnap
Definition EditorLayer.h:51
glm::vec4 m_SquareColor
Definition EditorLayer.h:93
glm::vec2 m_ViewportSize
Definition EditorLayer.h:45
bool OnKeyPressed(KeyPressedEvent &e)
Definition EditorLayer.cpp:669
bool m_PrimaryCamera
Definition EditorLayer.h:47
float m_squareRotation
Definition EditorLayer.h:82
OrthographicCameraController m_CameraController
Definition EditorLayer.h:53
Ref< Scene > m_ActiveScene
Definition EditorLayer.h:35
glm::vec4 m_TextureTintColor2
Definition EditorLayer.h:95
Ref< SubTexture2D > m_SubTextureTown
Definition EditorLayer.h:72
bool m_UseSpecialQuadColor
Definition EditorLayer.h:99
Ref< Scene > m_EditorScene
Definition EditorLayer.h:36
glm::vec4 m_BackgroundColor
Definition EditorLayer.h:96
Ref< Texture2D > m_CheckerboardTexture
Definition EditorLayer.h:61
Entity m_CameraEntity
Definition EditorLayer.h:48
Ref< VertexArray > m_SquareVA
Definition EditorLayer.h:59
virtual void OnEvent(Event &e) override
Called when an event is dispatched to the layer.
Definition EditorLayer.cpp:657
int ParticleEmitCount
Definition EditorLayer.h:84
SceneState m_SceneState
Definition EditorLayer.h:42
virtual void OnUpdate(Timestep ts) override
Called every frame to update the layer with the given timestep.
Definition EditorLayer.cpp:234
float m_textureScale
Definition EditorLayer.h:81
SceneHierarchyPanel m_SceneHierarchyPanel
Definition EditorLayer.h:33
Ref< Texture2D > m_SpriteSheetRocks
Definition EditorLayer.h:67
Ref< SubTexture2D > m_SubTextureFire
Definition EditorLayer.h:70
float m_specialQuadRotation
Definition EditorLayer.h:83
virtual void OnAttach() override
Called when the layer is attached to the application.
Definition EditorLayer.cpp:45
bool scene1
Definition EditorLayer.h:90
void SaveSceneAs()
Definition EditorLayer.cpp:744
bool useEntityScene
Definition EditorLayer.h:91
Entity m_SmokeEntity
Definition EditorLayer.h:56
bool scene2
Definition EditorLayer.h:90
Entity m_FireEntity
Definition EditorLayer.h:56
Ref< Framebuffer > m_Framebuffer
Definition EditorLayer.h:77
bool m_ViewportHovered
Definition EditorLayer.h:44
Ref< Texture2D > m_SpriteSheetFire
Definition EditorLayer.h:63
virtual ~EditorLayer()=default
Ref< Texture2D > m_SpriteSheetSmoke
Definition EditorLayer.h:64
virtual void OnDetach() override
Called when the layer is detached from the application.
Definition EditorLayer.cpp:229
virtual void OnImGuiRender() override
Called when the layer should render its ImGui components.
Definition EditorLayer.cpp:425
Ref< Texture2D > m_SpriteSheetTown
Definition EditorLayer.h:65
void ResetScene()
Definition EditorLayer.cpp:755
Represents an entity in a scene.
Definition Entity.h:14
Stack-based templated event dispatcher.
Definition Event.h:68
EventDispatcher(Event &event)
Construct an EventDispatcher for a specific event.
Definition Event.h:78
Abstract base class for all events.
Definition Event.h:37
Cross-platform file dialog utilities.
Definition PlatformUtils.h:10
static std::string SaveFile(const char *filter)
Opens a file dialog to select a location to save a file.
Definition WindowsPlatformUtils.cpp:29
static std::string OpenFile(const char *filter)
Opens a file dialog to select a file to open.
Definition WindowsPlatformUtils.cpp:12
Definition PlatformUtils.h:28
static void Initialize()
Definition WindowsPlatformUtils.cpp:66
static std::string m_RootEditorDirectory
Definition PlatformUtils.h:38
static std::string m_ProjectsDirectory
Definition PlatformUtils.h:41
static std::string GetCurrentWorkingDirectory()
Definition WindowsPlatformUtils.cpp:97
static std::string m_AssetsDirectory
Definition PlatformUtils.h:40
static std::string m_ResourcesDirectory
Definition PlatformUtils.h:39
static std::string GetTravelingUpPath(const std::string &path)
Definition WindowsPlatformUtils.cpp:112
static std::string m_RootEngineDirectory
Definition PlatformUtils.h:37
static std::string m_CurrentProjectDirectory
Definition PlatformUtils.h:42
static std::string GetAbsolutePath(const std::string &relativePath)
Definition WindowsPlatformUtils.cpp:104
static bool m_Initialized
Definition PlatformUtils.h:36
static bool IsInitialized()
Definition PlatformUtils.h:34
Definition ImGuiLayer.h:13
virtual void SetBlockEvents(bool block)
Definition ImGuiLayer.h:26
Base input class for querying input states.
Definition Input.h:12
static bool IsMouseButtonPressed(int button)
Checks if the specified mouse button is currently pressed.
Definition WindowsInput.cpp:16
static bool IsKeyPressed(int keycode)
Checks if the specified key is currently pressed.
Definition WindowsInput.cpp:9
int GetKeyCode() const
Get the key code associated with the event.
Definition KeyEvent.h:20
Event for registering key press.
Definition KeyEvent.h:37
int GetRepeatCount() const
Get the repeat count of the key press event.
Definition KeyEvent.h:48
Represents a reusable application layer that receives lifecycle callbacks (attach,...
Definition Layer.h:17
Manages an ordered stack of Layer pointers. Layers can be pushed or popped and the stack can be itera...
Definition LayerStack.h:16
Definition OrthographicCameraController.h:26
Definition ParticleSystem.h:25
A static class that provides an interface for issuing rendering commands.
Definition RenderCommand.h:10
static void Clear()
Clears the rendering buffers.
Definition RenderCommand.h:32
A 2D renderer for drawing quads and sprites.
Definition Renderer2D.h:17
static void ResetStats()
Resets the rendering statistics.
Definition Renderer2D.cpp:497
static void EndScene()
Ends the current scene.
Definition Renderer2D.cpp:160
static Statistics GetStats()
Retrieves the current rendering statistics.
Definition Renderer2D.cpp:502
An abstract class defining the interface for a rendering API.
Definition RendererAPI.h:11
API
API.
Definition RendererAPI.h:14
@ OpenGL
Definition RendererAPI.h:16
Definition SceneSerializer.h:7
bool Deserialize(const std::string &filepath)
Definition SceneSerializer.cpp:206
void Serialize(const std::string &filepath)
Definition SceneSerializer.cpp:179
Represents a time step in seconds.
Definition Timestep.h:12
Event for registering window close.
Definition ApplicationEvent.h:49
Abstract interface representing an application window.
Definition Window.h:43
virtual uint32_t GetWidth() const =0
Retrieves the width of the window.
virtual ~Window()
Definition Window.h:47
virtual void * GetNativeWindow() const =0
Retrieves the native window handle.
static Scope< Window > Create(const WindowProps &props=WindowProps())
Creates a window instance with the specified properties.
Definition WindowsWindow.cpp:20
virtual void SetEventCallback(const EventCallbackFn &callback)=0
Sets the callback function for window events.
virtual void OnUpdate()=0
Called every frame to update the window.
virtual bool IsVSync() const =0
Checks if vertical synchronization (VSync) is enabled.
virtual void SetVSync(bool enabled)=0
Sets whether vertical synchronization (VSync) is enabled.
virtual uint32_t GetHeight() const =0
Retrieves the height of the window.
Event for registering window resize.
Definition ApplicationEvent.h:16
@ RightShift
Definition KeyCodes.h:143
@ RightControl
Definition KeyCodes.h:144
@ Q
Definition KeyCodes.h:54
@ O
Definition KeyCodes.h:52
@ LeftShift
Definition KeyCodes.h:139
@ LeftControl
Definition KeyCodes.h:140
@ N
Definition KeyCodes.h:51
@ S
Definition KeyCodes.h:56
Definition Math.cpp:7
bool DecomposeTransform(const glm::mat4 &transform, glm::vec3 &translation, glm::vec3 &rotation, glm::vec3 &scale)
Decomposes a transformation matrix into its translation, rotation, and scale components.
Definition Math.cpp:10
@ ButtonLeft
Definition MouseButtonCodes.h:26
TEMPORARY.
Definition WindowsInput.cpp:7
std::string WorkingDirectory
Definition Application.h:22
WindowMode Mode
Definition Application.h:26
constexpr Ref< T > CreateRef(Args &&... args)
Creates a Ref (shared_ptr) for the given type and constructor arguments.
Definition Defines_Macros.h:72
uint32_t Width
Definition Application.h:24
constexpr Scope< T > CreateScope(Args &&... args)
Creates a Scope (unique_ptr) for the given type and constructor arguments.
Definition Defines_Macros.h:52
Application * CreateApplication()
Definition VesperEditorApp.cpp:23
bool EnableImGui
Definition Application.h:27
WindowMode
WIP.
Definition Window.h:16
@ Fullscreen
Definition Window.h:18
@ Borderless
Definition Window.h:19
@ Windowed
Definition Window.h:17
uint32_t Height
Definition Framebuffer.h:10
uint32_t Width
Definition Framebuffer.h:10
bool EnableVSync
Definition Application.h:28
std::string ApplicationName
Definition Application.h:21
static void DisplayVesperInfo_ImGui()
Definition VesperImGui.h:7
uint32_t Height
Definition Application.h:25
WIP.
Definition Application.h:20
Specification for creating a Framebuffer.
Definition Framebuffer.h:9
Definition ParticleSystem.h:9
Holds the data for window configuration.
Definition Window.h:23
uint32_t Height
Definition Window.h:26
uint32_t Width
Definition Window.h:25
std::string Title
Definition Window.h:24