File: main.cpp

package info (click to toggle)
renderdoc 1.24%2Bdfsg-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 105,156 kB
  • sloc: cpp: 759,405; ansic: 309,460; python: 26,606; xml: 22,599; java: 11,365; cs: 7,181; makefile: 6,707; yacc: 5,682; ruby: 4,648; perl: 3,461; sh: 2,354; php: 2,119; lisp: 1,835; javascript: 1,524; tcl: 1,068; ml: 747
file content (712 lines) | stat: -rw-r--r-- 19,232 bytes parent folder | download
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2022 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include <stdio.h>
#include <string.h>
#include <string>

#include "test_common.h"

#pragma warning(push)
#pragma warning(disable : 4127)    // conditional expression is constant
#pragma warning(disable : 4244)    // conversion from 'x' to 'y', possible loss of data
#pragma warning(disable : 4505)    // unreferenced local function has been removed
#pragma warning(disable : 4701)    // potentially uninitialized local variable used

#define NK_IMPLEMENTATION
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_ASSERT(expr) TEST_ASSERT(expr, "nuklear assertion failed")
#include "3rdparty/nuklear/nuklear.h"

#if defined(WIN32)

#define NK_GDI_IMPLEMENTATION
#include "3rdparty/nuklear/nuklear_gdi.h"

static LRESULT CALLBACK NuklearWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
  if(msg == WM_CLOSE)
  {
    DestroyWindow(wnd);
    return 0;
  }
  if(msg == WM_DESTROY)
  {
    PostQuitMessage(0);
    return 0;
  }
  if(msg == WM_KEYDOWN && wparam == VK_ESCAPE)
  {
    PostQuitMessage(0);
    return 0;
  }

  if(nk_gdi_handle_event(wnd, msg, wparam, lparam))
    return 0;

  return DefWindowProcW(wnd, msg, wparam, lparam);
}

WNDCLASSW wc = {};
HWND wnd = NULL;
HDC dc = NULL;
GdiFont *font = NULL;

nk_context *NuklearInit(int width, int height, const char *title)
{
  wc.style = CS_DBLCLKS;
  wc.lpfnWndProc = NuklearWndProc;
  wc.hInstance = GetModuleHandleA(NULL);
  wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  wc.lpszClassName = L"NuklearWindowClass";
  RegisterClassW(&wc);

  int len = (int)strlen(title);

  int wsize = MultiByteToWideChar(CP_UTF8, 0, title, len, NULL, 0);
  WCHAR *wstr = (WCHAR *)_alloca(wsize * sizeof(wchar_t) + 2);
  wstr[wsize] = 0;
  MultiByteToWideChar(CP_UTF8, 0, title, len, wstr, wsize);

  RECT rect = {0, 0, width, height};
  AdjustWindowRectEx(&rect, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, FALSE,
                     WS_EX_WINDOWEDGE);
  wnd = CreateWindowExW(
      WS_EX_WINDOWEDGE, wc.lpszClassName, wstr, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE,
      (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2,
      (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2, rect.right - rect.left,
      rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL);

  dc = GetDC(wnd);

  font = nk_gdifont_create("Arial", 14);
  return nk_gdi_init(font, dc, width, height);
}

bool NuklearTick(nk_context *ctx)
{
  MSG msg = {};
  UpdateWindow(wnd);

  nk_input_begin(ctx);
  // Check to see if any messages are waiting in the queue
  while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
  {
    // Translate the message and dispatch it to WindowProc()
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  nk_input_end(ctx);

  if(!IsWindowVisible(wnd) || msg.message == WM_QUIT)
    return false;

  return true;
}

void NuklearRender()
{
  nk_gdi_render(nk_rgb(30, 30, 30));
}

void NuklearShutdown()
{
  nk_gdifont_del(font);
  ReleaseDC(wnd, dc);
  DestroyWindow(wnd);
  UnregisterClassW(wc.lpszClassName, wc.hInstance);
}

#elif defined(__linux__)

#define NK_XLIB_IMPLEMENTATION
#include "3rdparty/nuklear/nuklear_xlib.h"

Display *dpy = NULL;
Colormap cmap = 0;
Window win = 0;
int screen = 0;
XFont *font = NULL;

nk_context *NuklearInit(int width, int height, const char *title)
{
  dpy = XOpenDisplay(NULL);
  if(!dpy)
    return NULL;
  Window root = DefaultRootWindow(dpy);
  screen = XDefaultScreen(dpy);
  Visual *vis = XDefaultVisual(dpy, screen);
  cmap = XCreateColormap(dpy, root, vis, AllocNone);

  XSetWindowAttributes swa = {};
  swa.colormap = cmap;
  swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPress | ButtonReleaseMask |
                   ButtonMotionMask | Button1MotionMask | Button3MotionMask | Button4MotionMask |
                   Button5MotionMask | PointerMotionMask | KeymapStateMask;
  win = XCreateWindow(dpy, root, 0, 0, width, height, 0, XDefaultDepth(dpy, screen), InputOutput,
                      vis, CWEventMask | CWColormap, &swa);

  XStoreName(dpy, win, title);
  XMapWindow(dpy, win);
  Atom wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  XSetWMProtocols(dpy, win, &wm_delete_window, 1);

  /* GUI */
  font = nk_xfont_create(dpy, "fixed");
  return nk_xlib_init(font, dpy, screen, win, width, height);
}

bool NuklearTick(nk_context *ctx)
{
  XEvent evt;

  nk_input_begin(ctx);
  while(XPending(dpy))
  {
    XNextEvent(dpy, &evt);
    if(evt.type == ClientMessage)
      return false;
    if(XFilterEvent(&evt, win))
      continue;
    nk_xlib_handle_event(dpy, screen, win, &evt);
  }
  nk_input_end(ctx);

  return true;
}

void NuklearRender()
{
  XClearWindow(dpy, win);
  nk_xlib_render(win, nk_rgb(30, 30, 30));
  XFlush(dpy);
}

void NuklearShutdown()
{
  nk_xfont_del(dpy, font);
  nk_xlib_shutdown();
  XUnmapWindow(dpy, win);
  XFreeColormap(dpy, cmap);
  XDestroyWindow(dpy, win);
  XCloseDisplay(dpy);
}

#elif defined(__APPLE__)

#include "apple/official/metal-cpp.h"
extern "C" void *const NSDefaultRunLoopMode;

#define NK_APPKIT_IMPLEMENTATION
#include "apple/nuklear_appkit.h"

static nk_appkit_window *window;
static AppkitFont *font;
static NS::Application *pSharedApplication = NULL;

nk_context *NuklearInit(int width, int height, const char *title)
{
  if(!nk_appkit_core_initialize())
    exit(EXIT_FAILURE);

  pSharedApplication = NS::Application::sharedApplication();

  window = nk_appkit_window_create(width, height, title);
  if(!window)
    exit(EXIT_FAILURE);

  nk_context *ctx = nk_appkit_create(window);
  font = nk_appkit_create_font("Menlo Regular", 9);
  nk_appkit_init(font);
  return ctx;
}

bool NuklearTick(nk_context *ctx)
{
  NS::AutoreleasePool *pAutoreleasePool = NS::AutoreleasePool::alloc()->init();
  while(true)
  {
    NS::Event *event = pSharedApplication->nextEventMatchingMask(
        (int)NS::EventMaskAny, NS::Date::distantPast(), (NS::String *)NSDefaultRunLoopMode, true);
    if(event == NULL)
      break;
    pSharedApplication->sendEvent(event);
  }
  pAutoreleasePool->release();
  nk_appkit_new_frame();

  if(nk_appkit_window_is_closed(window))
    return false;

  return true;
}

void NuklearRender()
{
  nk_appkit_render(nk_rgb(30, 30, 30));
}

void NuklearShutdown()
{
  nk_appkit_delete_font(font);
  nk_appkit_shutdown();
  nk_appkit_window_delete(window);
  nk_appkit_core_shutdown();
}

#else

#error UNKNOWN PLATFORM

#endif

// nuklear
#pragma warning(pop)

std::vector<TestMetadata> &test_list()
{
  static std::vector<TestMetadata> list;
  return list;
}

void check_tests(int argc, char **argv)
{
  std::vector<TestMetadata> &tests = test_list();

  for(TestMetadata &test : tests)
    test.test->Prepare(argc, argv);
}

void RegisterTest(TestMetadata test)
{
  test_list().push_back(test);
}

#if defined(_WIN64)
#pragma warning(disable : 4091)

#include <ImageHlp.h>

LONG exceptionHandler(_EXCEPTION_POINTERS *ExceptionInfo)
{
  TEST_ERROR("Unhandled exception, code %08x", ExceptionInfo->ExceptionRecord->ExceptionCode);

  if(HMODULE dbghelp = GetModuleHandleA("dbghelp.dll"))
  {
    using PFN_getLine = decltype(&SymGetLineFromAddr64);

    PFN_getLine getLine = (PFN_getLine)GetProcAddress(dbghelp, "SymGetLineFromAddr64");

    if(getLine)
    {
      DWORD64 stack[64] = {};

      USHORT num = RtlCaptureStackBackTrace(1, 63, (void **)stack, NULL);

      for(USHORT i = 0; i < num; i++)
      {
        DWORD offs = 0;
        IMAGEHLP_LINE64 line = {};
        getLine(GetCurrentProcess(), stack[i], &offs, &line);

        if(line.FileName && line.FileName[0])
        {
          TEST_LOG("[%u] %s:%u", i, line.FileName, line.LineNumber);
        }
        else
        {
          HMODULE mod = NULL;
          GetModuleHandleExA(
              GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
              (const char *)stack[i], &mod);

          if(mod)
          {
            char file[512] = {0};
            GetModuleFileNameA(mod, file, 511);

            TEST_LOG("[%u] %s+0x%x", i, file, stack[i] - (DWORD64)mod);
          }
          else
          {
            TEST_LOG("[%u] ??? %p", i, stack[i]);
          }
        }
      }

      return EXCEPTION_EXECUTE_HANDLER;
    }
  }

  TEST_LOG("No callstack available");

  return EXCEPTION_EXECUTE_HANDLER;
}
#endif

int main(int argc, char **argv)
{
  std::vector<TestMetadata> &tests = test_list();

  std::sort(tests.begin(), tests.end());

  if(argc >= 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h") || !strcmp(argv[1], "-?") ||
                   !strcmp(argv[1], "/help") || !strcmp(argv[1], "/h") || !strcmp(argv[1], "/?")))
  {
    printf(R"(RenderDoc testing demo program

Usage: %s Test_Name [test_options]

  --help                        Print this help message.
  --list                        Lists all tests, with name, API, description, availability.
  --list-raw                    Lists the available test names only, one per line.
  --validate
  --debug                       Run the demo with API validation enabled.
  --gpu [identifier]            Try to select the corresponding GPU where available and possible
                                through the API. Identifier is e.g. 'nv' or 'amd', or can be '1080'
  --warp                        On D3D APIs, use the software rasterizer.
  --width / -w                  Specify the window width.
  --height / -h                 Specify the window height.
  --frames <n>
  --max-frames <n>
  --frame-count <n>             Only run the demo for this number of frames
  --data <path>                 Specfiy where extended data should come from.
                                By default in the path in $RENDERDOC_DEMOS_DATA
                                environment variable, or else in the data/demos
                                folder next to the executable.
)",
           argc == 0 ? "demos" : argv[0]);

    fflush(stdout);
    return 1;
  }

  if(argc >= 2 && !strcmp(argv[1], "--list"))
  {
    check_tests(argc, argv);

    TestAPI prev = TestAPI::Count;

    for(const TestMetadata &test : tests)
    {
      if(test.API != prev)
      {
        if(prev != TestAPI::Count)
          printf("\n\n");
        printf("======== %s tests ========\n\n", APIName(test.API));
      }

      prev = test.API;

      printf("%s: %s", test.Name, test.IsAvailable() ? "Available" : "Unavailable");

      if(!test.IsAvailable())
        printf(" because %s", test.AvailMessage());

      printf("\n\t%s\n\n", test.Description);
    }

    fflush(stdout);
    return 1;
  }

  if(argc >= 2 && !strcmp(argv[1], "--list-raw"))
  {
    check_tests(argc, argv);

    // output TSV
    printf("Name\tAvailable\tAvailMessage\n");

    for(const TestMetadata &test : tests)
    {
      printf("%s\t%s\t%s\n", test.Name, test.IsAvailable() ? "True" : "False",
             test.IsAvailable() ? "Available" : test.AvailMessage());
    }

    fflush(stdout);
    return 1;
  }

  if(tests.empty())
  {
    fprintf(stderr, "No tests registered\n");
    fflush(stderr);
    return 1;
  }

  // Check if the first arg is a valid test name. If it isn't,
  // allow the UI to appear, so that flags can be used with the UI
  bool validTestArg = false;
  if(argc >= 2)
  {
    for(const TestMetadata &test : tests)
    {
      if(!strcmp(test.Name, argv[1]))
      {
        validTestArg = true;
        break;
      }
    }
  }

  std::string testchoice;

#if 0
  testchoice = "Hardcoded test name";
#endif

  if(!testchoice.empty())
  {
    // hardcoded test, ignore everything else
  }
  else if(tests.size() == 1)
  {
    // if there's only one test we've probably hardcoded this for a repro. Launch it
    testchoice = tests[0].Name;
  }
  else if(validTestArg)
  {
    testchoice = argv[1];
  }
  else
  {
    check_tests(argc, argv);

    const int width = 400, height = 575;

    nk_context *ctx = NuklearInit(width, height, "RenderDoc Test Program");

    if(!ctx)
      return 1;

    int curtest = 0;
    bool allow[(int)TestAPI::Count] = {};
    bool nofilters = true;
    const char *allow_names[] = {
        "D3D11", "Vulkan", "OpenGL", "D3D12",
    };

    char name_filter[256] = {};

    static_assert(ARRAY_COUNT(allow) == ARRAY_COUNT(allow_names), "Mismatched array");

    while(NuklearTick(ctx))
    {
      if(nk_begin(ctx, "Demo", nk_rect(0, 0, (float)width, (float)height), NK_WINDOW_NO_SCROLLBAR))
      {
        nk_layout_row_dynamic(ctx, 100, 1);
        if(nk_group_begin(ctx, "Test Filter",
                          NK_WINDOW_BORDER | NK_WINDOW_TITLE | NK_WINDOW_NO_SCROLLBAR))
        {
          nk_layout_row_dynamic(ctx, 30, ARRAY_COUNT(allow_names) + 1);

          nk_label(ctx, "API Filter:", NK_TEXT_LEFT);

          nofilters = true;
          for(size_t i = 0; i < ARRAY_COUNT(allow); i++)
          {
            std::string text = allow_names[i];

            allow[i] = nk_check_label(ctx, text.c_str(), allow[i]) != 0;
            nofilters &= !allow[i];
          }

          nk_layout_row_begin(ctx, NK_STATIC, 20, 2);
          nk_layout_row_push(ctx, 60.0f);
          nk_label(ctx, "Name Filter:", NK_TEXT_LEFT);
          nk_layout_row_push(ctx, 280.0f);
          nk_edit_string_zero_terminated(ctx, NK_EDIT_FIELD, name_filter, 256, NULL);
          nk_layout_row_end(ctx);

          nk_group_end(ctx);
        }

        nk_layout_row_dynamic(ctx, 270, 1);
        if(nk_group_begin(ctx, "Test", NK_WINDOW_BORDER | NK_WINDOW_TITLE))
        {
          float prevSpacing = 0;
          std::swap(prevSpacing, ctx->style.window.spacing.y);

          nk_layout_row_dynamic(ctx, 20, 1);

          std::string lower_filter = strlower(name_filter);

          for(int i = 0; i < (int)tests.size(); i++)
          {
            if(!tests[i].IsAvailable())
              continue;

            std::string lower_name = strlower(tests[i].Name);

            // apply filters
            if((!allow[(int)tests[i].API] && !nofilters) ||
               (!lower_filter.empty() && !strstr(lower_name.c_str(), lower_filter.c_str())))
            {
              // if this was the selected test, unselect it. The next unfiltered test will grab it
              if(curtest == i)
                curtest = -1;

              continue;
            }

            // grab the current test, if none is selected (see above)
            if(curtest == -1)
              curtest = i;

            if(nk_select_label(ctx, tests[i].Name, NK_TEXT_LEFT, curtest == i))
              curtest = i;
          }

          std::swap(prevSpacing, ctx->style.window.spacing.y);
          nk_group_end(ctx);
        }

        nk_layout_row_dynamic(ctx, 150, 1);

        TestMetadata &selected_test = tests[curtest >= 0 ? curtest : 0];

        if(nk_group_begin(ctx, "Test Information", NK_WINDOW_BORDER | NK_WINDOW_TITLE))
        {
          if(curtest >= 0)
          {
            nk_layout_row_begin(ctx, NK_STATIC, 20, 2);
            nk_layout_row_push(ctx, 60.0f);
            nk_label(ctx, "Test name: ", NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_LEFT);
            nk_layout_row_push(ctx, 280.0f);
            nk_label(ctx, selected_test.Name, NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_LEFT);
            nk_layout_row_end(ctx);

            nk_layout_row_begin(ctx, NK_STATIC, 20, 2);
            nk_layout_row_push(ctx, 60.0f);
            nk_label(ctx, "API:", NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_LEFT);
            nk_layout_row_push(ctx, 280.0f);
            nk_label(ctx, APIName(selected_test.API), NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_LEFT);
            nk_layout_row_end(ctx);

            nk_layout_row_begin(ctx, NK_DYNAMIC, 50, 1);
            nk_layout_row_push(ctx, 1.0f);
            nk_label_wrap(ctx, selected_test.Description);
            nk_layout_row_end(ctx);
          }
          else
          {
            nk_layout_row_begin(ctx, NK_DYNAMIC, 20, 1);
            nk_layout_row_push(ctx, 1.0f);
            nk_label(ctx, "No test selected", NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_LEFT);
            nk_layout_row_end(ctx);
          }

          nk_group_end(ctx);
        }

        nk_layout_row_dynamic(ctx, 30, 1);

        if(curtest >= 0)
        {
          if(nk_button_label(ctx, "Run"))
          {
            testchoice = selected_test.Name;
            break;
          }
        }
        else
        {
          nk_label(ctx, "No test selected", NK_TEXT_ALIGN_TOP | NK_TEXT_ALIGN_CENTERED);
        }
      }
      nk_end(ctx);

      NuklearRender();
    }

    NuklearShutdown();
  }

  if(testchoice.empty())
    return 0;

#if defined(_WIN64)
  SetUnhandledExceptionFilter(&exceptionHandler);
#endif

  for(const TestMetadata &test : tests)
  {
    if(testchoice == test.Name)
    {
      TEST_LOG("Running '%s'", test.Name);
      test.test->Prepare(argc, argv);
      test.test->SetName(test.Name);

      if(!test.IsAvailable())
      {
        TEST_ERROR("%s is not available: %s", test.Name, test.test->Avail.c_str());
        return 5;
      }

      int ret = test.test->main();
      test.test->Shutdown();
      return ret;
    }
  }

  TEST_ERROR("%s is not a known test", argv[1]);

  return 2;
}

#if defined(WIN32)
int WINAPI wWinMain(_In_ HINSTANCE hInst, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine,
                    _In_ int nShowCmd)
{
  LPWSTR *wargv;
  int argc;

  if(AttachConsole(ATTACH_PARENT_PROCESS))
  {
    FILE *dummy = NULL;
    freopen_s(&dummy, "CONOUT$", "w", stdout);
    freopen_s(&dummy, "CONOUT$", "w", stderr);
  }

  wargv = CommandLineToArgvW(GetCommandLineW(), &argc);

  char **argv = new char *[argc];
  for(int i = 0; i < argc; i++)
  {
    // allocate pessimistically
    int allocSize = (int)wcslen(wargv[i]) * 4 + 1;

    argv[i] = new char[allocSize];

    WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, &argv[i][0], allocSize, NULL, NULL);
  }

  main(argc, argv);

  delete[] argv;
  LocalFree(wargv);
}

#endif