forked from dfranx/SHADERed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
387 lines (320 loc) · 11.1 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#ifdef _WIN32
#include <windows.h>
#endif
#include <SHADERed/EditorEngine.h>
#include <SHADERed/Engine/GeometryFactory.h>
#include <SHADERed/Objects/AudioShaderStream.h>
#include <SHADERed/Objects/Logger.h>
#include <SHADERed/Objects/Settings.h>
#include <SDL2/SDL.h>
#include <glslang/Public/ShaderLang.h>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <thread>
#include <stb/stb_image.h>
#include <stb/stb_image_write.h>
#if defined(__linux__) || defined(__unix__)
#include <libgen.h>
#include <unistd.h>
#endif
#if defined(NDEBUG) && defined(_WIN32)
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#endif
// SDL defines main
#undef main
void SetIcon(SDL_Window* wnd);
void SetDpiAware();
int main(int argc, char* argv[])
{
std::filesystem::path cmdDir = std::filesystem::current_path();
if (argc > 0) {
if (std::filesystem::exists(std::filesystem::path(argv[0]).parent_path())) {
std::filesystem::current_path(std::filesystem::path(argv[0]).parent_path());
ed::Logger::Get().Log("Setting current_path to " + std::filesystem::current_path().generic_string());
}
}
#if defined(__linux__) || defined(__unix__)
// currently the only supported argument is a path to set the working directory... dont do this check if user wants to explicitly set the working directory,
// TODO: if more arguments get added, use different methods to check if working directory is being set explicitly
if (argc <= 1) {
char result[PATH_MAX];
ssize_t readlinkRes = readlink("/proc/self/exe", result, PATH_MAX);
std::string exePath = "";
if (readlinkRes != -1)
exePath = std::string(dirname(result));
std::vector<std::string> toCheck = {
"/../share/SHADERed",
"/../share/shadered"
// TODO: maybe more paths here?
};
for (const auto& wrkpath : toCheck) {
if (std::filesystem::exists(exePath + wrkpath)) {
std::filesystem::current_path(exePath + wrkpath);
ed::Logger::Get().Log("Setting current_path to " + std::filesystem::current_path().generic_string());
break;
}
}
}
#endif
// create data directory on startup
if (!std::filesystem::exists("./data/"))
std::filesystem::create_directory("./data/");
// delete log.txt on startup
if (std::filesystem::exists("./log.txt")) {
std::error_code errCode;
std::filesystem::remove("./log.txt", errCode);
}
// set stb_image flags
stbi_flip_vertically_on_write(1);
stbi_set_flip_vertically_on_load(1);
// start glslang process
bool glslangInit = glslang::InitializeProcess();
ed::Logger::Get().Log("Initializing glslang...");
if (glslangInit)
ed::Logger::Get().Log("Finished glslang initialization");
else
ed::Logger::Get().Log("Failed to initialize glslang", true);
// init sdl2
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) {
ed::Logger::Get().Log("Failed to initialize SDL2", true);
ed::Logger::Get().Save();
return 0;
} else
ed::Logger::Get().Log("Initialized SDL2");
// load window size
short wndWidth = 800, wndHeight = 600, wndPosX = -1, wndPosY = -1;
bool fullscreen = false, maximized = false, perfMode = false;
std::ifstream preload("data/preload.dat");
if (preload.is_open()) {
ed::Logger::Get().Log("Loading window information from data/preload.dat");
preload.read(reinterpret_cast<char*>(&wndWidth), 2);
preload.read(reinterpret_cast<char*>(&wndHeight), 2);
preload.read(reinterpret_cast<char*>(&wndPosX), 2);
preload.read(reinterpret_cast<char*>(&wndPosY), 2);
fullscreen = preload.get();
maximized = preload.get();
if (preload.peek() != EOF)
perfMode = preload.get();
preload.close();
// clamp to desktop size
SDL_DisplayMode desk;
SDL_GetCurrentDisplayMode(0, &desk);
if (wndWidth > desk.w)
wndWidth = desk.w;
if (wndHeight > desk.h)
wndHeight = desk.h;
} else {
ed::Logger::Get().Log("File data/preload.dat doesnt exist", true);
ed::Logger::Get().Log("Deleting data/workspace.dat", true);
std::error_code errCode;
std::filesystem::remove("./data/workspace.dat", errCode);
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // double buffering
// open window
SDL_Window* wnd = SDL_CreateWindow("SHADERed", (wndPosX == -1) ? SDL_WINDOWPOS_CENTERED : wndPosX, (wndPosY == -1) ? SDL_WINDOWPOS_CENTERED : wndPosY, wndWidth, wndHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SetDpiAware();
SDL_SetWindowMinimumSize(wnd, 200, 200);
if (maximized)
SDL_MaximizeWindow(wnd);
if (fullscreen)
SDL_SetWindowFullscreen(wnd, SDL_WINDOW_FULLSCREEN_DESKTOP);
// get GL context
SDL_GLContext glContext = SDL_GL_CreateContext(wnd);
SDL_GL_MakeCurrent(wnd, glContext);
glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
// init glew
glewExperimental = true;
if (glewInit() != GLEW_OK) {
ed::Logger::Get().Log("Failed to initialize GLEW", true);
ed::Logger::Get().Save();
return 0;
} else
ed::Logger::Get().Log("Initialized GLEW");
// create engine
ed::EditorEngine engine(wnd, &glContext);
ed::Logger::Get().Log("Creating EditorEngine...");
engine.Create();
ed::Logger::Get().Log("Created EditorEngine");
// set window icon:
SetIcon(wnd);
// open an item if given in arguments
if (argc >= 2) {
ed::Logger::Get().Log("Openning a file provided through argument " + std::string(argv[1]));
engine.UI().Open(argv[1]);
std::filesystem::path argFile = cmdDir / std::filesystem::path(argv[1]);
if (std::filesystem::exists(argv[1]))
engine.UI().Open(argv[1]);
else if (std::filesystem::exists(argFile))
engine.UI().Open(argFile.generic_string().c_str());
}
engine.UI().SetPerformanceMode(perfMode);
engine.Interface().Renderer.AllowComputeShaders(GLEW_ARB_compute_shader);
// timer for time delta
ed::eng::Timer timer;
SDL_Event event;
bool run = true;
bool minimized = false;
bool hasFocus = true;
while (run) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
bool cont = true;
if (engine.Interface().Parser.IsProjectModified()) {
int btnID = engine.UI().AreYouSure();
if (btnID == 2)
cont = false;
}
if (cont) {
run = false;
ed::Logger::Get().Log("Received SDL_QUIT event -> quitting");
}
} else if (event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_MOVED || event.window.event == SDL_WINDOWEVENT_MAXIMIZED || event.window.event == SDL_WINDOWEVENT_RESIZED) {
Uint32 wndFlags = SDL_GetWindowFlags(wnd);
maximized = wndFlags & SDL_WINDOW_MAXIMIZED;
fullscreen = wndFlags & SDL_WINDOW_FULLSCREEN_DESKTOP;
minimized = false;
// cache window size and position
if (!maximized) {
int tempX = 0, tempY = 0;
SDL_GetWindowPosition(wnd, &tempX, &tempY);
wndPosX = tempX;
wndPosY = tempY;
SDL_GetWindowSize(wnd, &tempX, &tempY);
wndWidth = tempX;
wndHeight = tempY;
}
} else if (event.window.event == SDL_WINDOWEVENT_MINIMIZED)
minimized = true;
else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
hasFocus = false;
else if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
hasFocus = true;
}
#if defined(_WIN32)
else if (event.type == SDL_SYSWMEVENT) {
// this doesn't work - it seems that SDL doesn't forward WM_DPICHANGED message
if (event.syswm.type == WM_DPICHANGED && ed::Settings::Instance().General.AutoScale) {
float dpi = 0.0f;
int wndDisplayIndex = SDL_GetWindowDisplayIndex(wnd);
SDL_GetDisplayDPI(wndDisplayIndex, &dpi, NULL, NULL);
ed::Settings::Instance().TempScale = dpi / 96.0f;
ed::Logger::Get().Log("Updating DPI to " + std::to_string(dpi / 96.0f));
}
}
#endif
engine.OnEvent(event);
}
if (!run) break;
float delta = timer.Restart();
engine.Update(delta);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
engine.Render();
SDL_GL_SwapWindow(wnd);
if (minimized && delta * 1000 < 33)
std::this_thread::sleep_for(std::chrono::milliseconds(33 - (int)(delta * 1000)));
else if (!hasFocus && ed::Settings::Instance().Preview.LostFocusLimitFPS && delta * 1000 < 16)
std::this_thread::sleep_for(std::chrono::milliseconds(16 - (int)(delta * 1000)));
}
engine.UI().Destroy();
// union for converting short to bytes
union {
short size;
char data[2];
} converter;
// save window size
std::ofstream save("data/preload.dat");
ed::Logger::Get().Log("Saving window information");
converter.size = wndWidth; // write window width
save.write(converter.data, 2);
converter.size = wndHeight; // write window height
save.write(converter.data, 2);
converter.size = wndPosX; // write window position x
save.write(converter.data, 2);
converter.size = wndPosY; // write window position y
save.write(converter.data, 2);
save.put(fullscreen);
save.put(maximized);
save.put(engine.UI().IsPerformanceMode());
save.close();
// close and free the memory
engine.Destroy();
// sdl2
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(wnd);
SDL_Quit();
ed::Logger::Get().Log("Destroyed EditorEngine and SDL2");
ed::Logger::Get().Save();
return 0;
}
void SetIcon(SDL_Window* wnd)
{
float dpi = 0.0f;
int wndDisplayIndex = SDL_GetWindowDisplayIndex(wnd);
SDL_GetDisplayDPI(wndDisplayIndex, &dpi, NULL, NULL);
dpi /= 96.0f;
stbi_set_flip_vertically_on_load(0);
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char* data = stbi_load(dpi == 1.0f ? "./icon_64x64.png" : "./icon_256x256.png", &width, &height, &orig_format, req_format);
if (data == NULL) {
ed::Logger::Get().Log("Failed to set window icon", true);
return;
}
int depth, pitch;
Uint32 pixel_format;
if (req_format == STBI_rgb) {
depth = 24;
pitch = 3 * width; // 3 bytes per pixel * pixels per row
pixel_format = SDL_PIXELFORMAT_RGB24;
} else { // STBI_rgb_alpha (RGBA)
depth = 32;
pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32;
}
SDL_Surface* surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)data, width, height,
depth, pitch, pixel_format);
if (surf == NULL) {
ed::Logger::Get().Log("Failed to create icon SDL_Surface", true);
stbi_image_free(data);
return;
}
SDL_SetWindowIcon(wnd, surf);
SDL_FreeSurface(surf);
stbi_image_free(data);
stbi_set_flip_vertically_on_load(1);
}
void SetDpiAware()
{
#if defined(_WIN32)
enum DpiAwareness {
Unaware,
System,
PerMonitor
};
typedef HRESULT(WINAPI * SetProcessDpiAwarenessFn)(DpiAwareness);
typedef BOOL(WINAPI * SetProcessDPIAwareFn)(void);
HINSTANCE lib = LoadLibraryA("Shcore.dll");
if (lib) {
SetProcessDpiAwarenessFn setProcessDpiAwareness = (SetProcessDpiAwarenessFn)GetProcAddress(lib, "SetProcessDpiAwareness");
if (setProcessDpiAwareness)
setProcessDpiAwareness(DpiAwareness::PerMonitor);
} else {
lib = LoadLibraryA("user32.dll");
if (lib) {
SetProcessDPIAwareFn setProcessDPIAware = (SetProcessDPIAwareFn)GetProcAddress(lib, "SetProcessDPIAware");
if (setProcessDPIAware)
setProcessDPIAware();
}
}
if (lib)
FreeLibrary(lib);
#endif
}