-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1446 lines (1145 loc) · 60.8 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
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <array>
#include <cassert>
#include <future>
#include <iostream>
#include <iomanip>
#include <list>
#include <string>
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define WIN32_LEAN_AND_MEAN
#include <dxgi1_6.h>
#include <Windows.h>
#include <wrl.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <GL/glew.h>
#include <GL/wglew.h>
#include <nvapi.h>
#include <cudaGL.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "OpenGLUtilities.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace Microsoft::WRL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace {
//------------------------------------------------------------------------------
// WGL_NV_gpu_affinity
//------------------------------------------------------------------------------
#ifndef WGL_NV_gpu_affinity
DECLARE_HANDLE(HGPUNV);
typedef struct _GPU_DEVICE {
DWORD cb;
CHAR DeviceName[32];
CHAR DeviceString[128];
DWORD Flags;
RECT rcVirtualScreen;
} GPU_DEVICE, *PGPU_DEVICE;
typedef BOOL(WINAPI* wglEnumGpusNV_f)(UINT iGpuIndex, HGPUNV* phGpu);
typedef BOOL(WINAPI* wglEnumGpuDevicesNV_f)(HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
typedef HDC(WINAPI* wglCreateAffinityDCNV_f)(const HGPUNV *phGpuList);
typedef BOOL(WINAPI* wglEnumGpusFromAffinityDCNV_f)(HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
typedef BOOL(WINAPI* wglDeleteDCNV_f)(HDC hdc);
wglEnumGpusNV_f wglEnumGpusNV = nullptr;
wglEnumGpuDevicesNV_f wglEnumGpuDevicesNV = nullptr;
wglCreateAffinityDCNV_f wglCreateAffinityDCNV = nullptr;
wglEnumGpusFromAffinityDCNV_f wglEnumGpusFromAffinityDCNV = nullptr;
wglDeleteDCNV_f wglDeleteDCNV = nullptr;
#endif // WGL_NV_gpu_affinity
//------------------------------------------------------------------------------
// Utilities
//------------------------------------------------------------------------------
void log_last_error_message()
{
const DWORD last_error = GetLastError();
LPSTR last_error_message = nullptr;
FormatMessageA((FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS),
NULL, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&last_error_message, 0, NULL);
fprintf(stderr, "%ju: %s", uintmax_t(last_error), last_error_message);
LocalFree(last_error_message);
}
LRESULT CALLBACK window_callback(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if ((uMsg == WM_ERASEBKGND) || (uMsg == WM_PAINT)) {
return TRUE;
}
if (uMsg == WM_DISPLAYCHANGE) {
std::cerr << "Warning: Display change occured. This application is not designed to handle such changes at runtime!" << std::endl;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void print_to_stream(std::ostream& stream, const NV_MOSAIC_GRID_TOPO& display_grid, const std::string& indent)
{
stream << indent << display_grid.rows << "x" << display_grid.columns << " (" << display_grid.displayCount << (display_grid.displayCount == 1 ? " display)" : " displays)") << std::endl;
stream << indent << display_grid.displaySettings.width << "x" << display_grid.displaySettings.height << " @ " << display_grid.displaySettings.freq << " Hz" << std::endl;
for (size_t r = 0; r < display_grid.rows; ++r) {
for (size_t c = 0; c < display_grid.columns; ++c) {
std::cout << indent << "[" << r << "," << c << "] 0x" << std::hex << std::setfill('0') << std::setw(8) << display_grid.displays[c + (r * display_grid.columns)].displayId << std::dec << std::endl;
}
std::cout << std::endl;
}
}
void print_display_flags_to_stream(std::ostream& stream, DWORD flags)
{
stream << "0x" << std::hex << std::setfill('0') << std::setw(8) << flags << std::dec;
if (flags != 0) {
bool first = true;
if ((flags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) == DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
if (first) { stream << " ("; }
else { stream << ", "; }
stream << "display attached";
first = false;
}
if ((flags & DISPLAY_DEVICE_PRIMARY_DEVICE) == DISPLAY_DEVICE_PRIMARY_DEVICE) {
if (first) { stream << " ("; }
else { stream << ", "; }
stream << "primary display";
first = false;
}
if ((flags & DISPLAY_DEVICE_UNSAFE_MODES_ON) == DISPLAY_DEVICE_UNSAFE_MODES_ON) {
if (first) { stream << " ("; }
else { stream << ", "; }
stream << "unsafe modes on";
first = false;
}
if (!first) { stream << ")"; }
}
}
void create_texture_backed_render_targets(GLuint* const framebuffers,
GLuint* const color_attachments,
size_t n,
size_t width,
size_t height)
{
glGenFramebuffers(GLsizei(n), framebuffers);
glGenTextures(GLsizei(n), color_attachments);
for (size_t i = 0; i < n; ++i) {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffers[i]);
glBindTexture(GL_TEXTURE_2D, color_attachments[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, GLsizei(width), GLsizei(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_attachments[i], 0);
const GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
throw std::runtime_error("Failed to validate framebuffer status!");
}
}
}
void delete_texture_backed_render_targets(const GLuint* const framebuffers, const GLuint* const color_attachments, size_t n)
{
glDeleteTextures(GLsizei(n), color_attachments);
glDeleteFramebuffers(GLsizei(n), framebuffers);
}
std::mutex render_threads_mutex;
std::list<std::future<void>> render_threads;
std::condition_variable start_render_threads_event;
bool start_render_threads_flag = false;
void start_render_threads(std::vector<HDC> display_contexts, std::vector<HGLRC> gl_contexts, const std::function<void(size_t)>& initialize, const std::function<void(size_t)>& render)
{
//------------------------------------------------------------------------------
// Check arguments.
assert(display_contexts.size() == gl_contexts.size());
//------------------------------------------------------------------------------
// Synchronize this function.
std::unique_lock<std::mutex> lock(render_threads_mutex);
start_render_threads_flag = false;
//------------------------------------------------------------------------------
// Start all threads and let them do their setup.
for (size_t thread_index = 0; thread_index < display_contexts.size(); ++thread_index) {
std::cout << "Starting render thread " << thread_index << std::endl;
const HDC display_context = display_contexts[thread_index];
const HGLRC gl_context = gl_contexts[thread_index];
std::promise<void> render_thread_ready;
std::future<void> render_thread = std::async(std::launch::async, [&render_thread_ready](
HDC display_context,
HGLRC gl_context,
const std::function<void(size_t)>& initialize,
const std::function<void(size_t)>& render,
size_t thread_index)
{
try {
//------------------------------------------------------------------------------
// Prepare for rendering.
if (wglMakeCurrent(display_context, gl_context) != TRUE) {
std::cerr << "Error: Failed to make OpenGL context current: ";
log_last_error_message();
throw std::runtime_error("Failed to make OpenGL context current!");
}
//------------------------------------------------------------------------------
// Check associated CUDA device.
unsigned int cuda_device_count = 0;
std::array<CUdevice, 4> cuda_devices;
if (cuGLGetDevices(&cuda_device_count, cuda_devices.data(), unsigned int(cuda_devices.size()), CU_GL_DEVICE_LIST_ALL) == CUDA_SUCCESS) {
for (size_t i = 0; i < cuda_device_count; ++i) {
std::cout << " CUDA device: " << cuda_devices[i] << std::endl;
}
}
//------------------------------------------------------------------------------
// Initialize.
initialize(thread_index);
//------------------------------------------------------------------------------
// Signal we are ready for rendering then wait for signal to start rendering.
render_thread_ready.set_value();
{
std::unique_lock<std::mutex> lock(render_threads_mutex);
start_render_threads_event.wait(lock, []() { return start_render_threads_flag; });
}
//------------------------------------------------------------------------------
// Render.
render(thread_index);
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Exception: <unknown>!" << std::endl;
}
}, display_context, gl_context, initialize, render, thread_index);
//------------------------------------------------------------------------------
// Wait for the thread to be ready for rendering.
render_thread_ready.get_future().wait();
render_threads.emplace_back(std::move(render_thread));
}
//------------------------------------------------------------------------------
// Signal all render threads to start.
start_render_threads_flag = true;
start_render_threads_event.notify_all();
}
void join_render_thread(std::future<void>& render_thread)
{
try {
render_thread.get();
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Exception: <unknown>!" << std::endl;
}
}
void join_render_threads()
{
std::unique_lock<std::mutex> lock(render_threads_mutex);
for (auto it = begin(render_threads); it != end(render_threads); ++it) {
if (it->valid() == false) {
continue;
}
join_render_thread(*it);
}
render_threads.clear();
}
bool try_join_render_threads(size_t timeout)
{
std::unique_lock<std::mutex> lock(render_threads_mutex);
for (auto it = begin(render_threads); it != end(render_threads);) {
if (it->valid() == false) {
it = render_threads.erase(it);
continue;
}
if (it->wait_for(std::chrono::milliseconds(timeout)) == std::future_status::ready) {
join_render_thread(*it);
it = render_threads.erase(it);
continue;
}
++it;
}
return render_threads.empty();
}
class RenderPoints
{
public:
static GLuint create_program()
{
static const char* const vs_string =
"#version 410\n"
"uniform vec4 u_rect;\n"
"uniform mat4 u_mvp;\n"
"out vec2 v_uv;\n"
"void main() {\n"
" int x = (gl_VertexID % 1024);\n"
" int y = (gl_VertexID / 1024);\n"
" vec2 uv = (vec2(x, y) * (1.0 / 1023.0));\n"
" gl_Position = (u_mvp * vec4((u_rect.xy + (uv * u_rect.zw)), 0.0, 1.0));\n"
" v_uv = vec2(uv.x, uv.y);\n"
"}\n";
static const char* const fs_string =
"#version 410\n"
"in vec2 v_uv;\n"
"out vec4 f_color;\n"
"void main() {\n"
" float vignette = pow(clamp(((v_uv.x * (1.0f - v_uv.x)) * (v_uv.y * (1.0f - v_uv.y)) * 36.0f), 0.0, 1.0), 4.0);\n"
" f_color = vec4((v_uv.rg * vignette), 0.0, 1.0);\n"
"}\n";
try {
const GLuint vertex_shader = toolbox::OpenGLShader::create_from_source(GL_VERTEX_SHADER, vs_string);
const GLuint fragment_shader = toolbox::OpenGLShader::create_from_source(GL_FRAGMENT_SHADER, fs_string);
toolbox::OpenGLProgram::attribute_location_list_t attribute_locations;
toolbox::OpenGLProgram::frag_data_location_list_t frag_data_locations;
const GLuint program = toolbox::OpenGLProgram::create_from_shaders(vertex_shader, fragment_shader, attribute_locations, frag_data_locations);
s_uniform_location_rect = glGetUniformLocation(program, "u_rect");
s_uniform_location_mvp = glGetUniformLocation(program, "u_mvp");
return program;
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "Exception: <unknown>!" << std::endl;
}
return 0;
}
static void set_rect(const float* const ndc_rect)
{
if (s_uniform_location_rect != -1) {
glUniform4fv(s_uniform_location_rect, 1, ndc_rect);
}
}
static void set_mvp(const float* const mvp)
{
if (s_uniform_location_mvp != -1) {
glUniformMatrix4fv(s_uniform_location_mvp, 1, GL_FALSE, mvp);
}
}
static void draw(GLuint& vao)
{
if (!vao) {
glGenVertexArrays(1, &vao);
}
glBindVertexArray(vao);
glDrawArrays(GL_POINTS, 0, (1024 * 1024));
}
private:
static GLint s_uniform_location_rect;
static GLint s_uniform_location_mvp;
};
GLint RenderPoints::s_uniform_location_rect = -1;
GLint RenderPoints::s_uniform_location_mvp = -1;
//------------------------------------------------------------------------------
// Global data.
//------------------------------------------------------------------------------
float rect[4] = { -1.0, -1.0, 2.0, 2.0 };
float mvp[16] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
};
uint8_t pixels[4][64 * 64 * 4];
typedef struct rect_s {
long m_x = 0;
long m_y = 0;
long m_width = 0;
long m_height = 0;
} rect_t;
rect_t virtual_screen;
long num_virtual_screen_monitors = 0;
std::vector<rect_t> virtual_screen_monitors;
//------------------------------------------------------------------------------
// Windows API
//------------------------------------------------------------------------------
int windows()
{
std::cout << "[Windows API]" << std::endl;
//------------------------------------------------------------------------------
// Get the Virtual Screen geometry.
virtual_screen.m_x = GetSystemMetrics(SM_XVIRTUALSCREEN);
virtual_screen.m_y = GetSystemMetrics(SM_YVIRTUALSCREEN);
virtual_screen.m_width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
virtual_screen.m_height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
num_virtual_screen_monitors = GetSystemMetrics(SM_CMONITORS);
std::cout << std::endl;
std::cout << "Virtual Screen origin: " << virtual_screen.m_x << " / " << virtual_screen.m_y << std::endl;
std::cout << "Virtual Screen size: " << virtual_screen.m_width << " x " << virtual_screen.m_height << std::endl;
std::cout << "Virtual Screen spans " << num_virtual_screen_monitors << " monitor(s)" << std::endl;
//------------------------------------------------------------------------------
// Enumerate display devices.
std::cout << std::endl;
DISPLAY_DEVICE display_device = {};
display_device.cb = sizeof(display_device);
DWORD display_device_index = 0;
while (EnumDisplayDevices(nullptr, display_device_index, &display_device, 0)) {
std::cout << "Display " << display_device.DeviceName << ", " << display_device.DeviceString << std::endl;
std::cout << " " << display_device.DeviceID << std::endl;
std::cout << " " << display_device.DeviceKey << std::endl;
std::cout << " "; print_display_flags_to_stream(std::cout, display_device.StateFlags); std::cout << std::endl;
++display_device_index;
DEVMODE device_mode = {};
device_mode.dmSize = sizeof(device_mode);
//------------------------------------------------------------------------------
// Enumerate/Get current display settings.
if ((0)) {
DWORD mode_index = 0;
while (EnumDisplaySettingsEx(display_device.DeviceName, mode_index, &device_mode, 0)) {
std::cout << " " << device_mode.dmPelsWidth << " x " << device_mode.dmPelsHeight << " @ " << device_mode.dmDisplayFrequency << " Hz" << std::endl;
++mode_index;
}
}
else {
if (EnumDisplaySettingsEx(display_device.DeviceName, ENUM_CURRENT_SETTINGS, &device_mode, 0)) {
std::cout << " " << device_mode.dmPelsWidth << " x " << device_mode.dmPelsHeight << " @ " << device_mode.dmDisplayFrequency << " Hz" << std::endl;
}
}
}
//------------------------------------------------------------------------------
// Enumerate display monitors.
//
// Each physical display is represented by a monitor handle of type HMONITOR.
std::cout << std::endl;
if (EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR monitor, HDC display_context, LPRECT virtual_screen_rect, LPARAM user_data) {
//------------------------------------------------------------------------------
// Add to list of monitors making up the virtual screen.
rect_t virtual_screen_monitor = {};
{
virtual_screen_monitor.m_x = virtual_screen_rect->left;
virtual_screen_monitor.m_y = virtual_screen_rect->top;
virtual_screen_monitor.m_width = (virtual_screen_rect->right - virtual_screen_rect->left);
virtual_screen_monitor.m_height = (virtual_screen_rect->bottom - virtual_screen_rect->top);
}
virtual_screen_monitors.push_back(virtual_screen_monitor);
//------------------------------------------------------------------------------
// Get additional monitor info.
MONITORINFOEX monitor_info = {};
monitor_info.cbSize = sizeof(monitor_info);
bool is_primary = false;
if (GetMonitorInfo(monitor, &monitor_info) != 0) {
std::cout << "Monitor " << monitor_info.szDevice << ": ";
is_primary = ((monitor_info.dwFlags & MONITORINFOF_PRIMARY) == MONITORINFOF_PRIMARY);
}
else {
std::cout << "Monitor 0x" << monitor << ": ";
}
std::cout << "(" << virtual_screen_monitor.m_x << " / " << virtual_screen_monitor.m_y << ") [" << virtual_screen_monitor.m_width << " x " << virtual_screen_monitor.m_height << "]";
if (is_primary) {
std::cout << " (primary)";
}
std::cout << std::endl;
return TRUE;
}, 0) == 0)
{
std::cerr << "Error: Failed to enumerate monitors!" << std::endl;
return EXIT_FAILURE;
}
if (virtual_screen_monitors.size() != num_virtual_screen_monitors) {
std::cerr << "Warning: EnumDisplayMonitors() returned more monitors than GetSystemMetrics() reported to be part of the virtual screen!" << std::endl;
}
//------------------------------------------------------------------------------
// ...
return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
// NVAPI based GPU query
//------------------------------------------------------------------------------
int nvapi()
{
std::cout << "[NVAPI]" << std::endl;
//------------------------------------------------------------------------------
// Initialize NVAPI.
if (NvAPI_Initialize() != NVAPI_OK) {
std::cerr << "Error: Failed to initialize NVAPI!" << std::endl;
return EXIT_FAILURE;
}
//------------------------------------------------------------------------------
// Print interface version string.
NvAPI_ShortString interface_version = {};
if (NvAPI_GetInterfaceVersionString(interface_version) == NVAPI_OK) {
std::cout << std::endl;
std::cout << "NVAPI interface version: " << interface_version << std::endl;
}
//------------------------------------------------------------------------------
// Get brief of current mosaic topology.
NV_MOSAIC_TOPO_BRIEF mosaic_topology = {};
mosaic_topology.version = NVAPI_MOSAIC_TOPO_BRIEF_VER;
NV_MOSAIC_DISPLAY_SETTING mosaic_display_settings = {};
mosaic_display_settings.version = NVAPI_MOSAIC_DISPLAY_SETTING_VER;
NvS32 mosaic_overlap_x = 0;
NvS32 mosaic_overlap_y = 0;
if (NvAPI_Mosaic_GetCurrentTopo(&mosaic_topology, &mosaic_display_settings, &mosaic_overlap_x, &mosaic_overlap_y) != NVAPI_OK) {
std::cerr << "Error: Failed to get mosaic topology!" << std::endl;
return EXIT_FAILURE;
}
//------------------------------------------------------------------------------
// If a topology is enabled show which one.
std::cout << std::endl;
if (mosaic_topology.enabled) {
std::cout << "Mosaic is ENABLED: ";
switch (mosaic_topology.topo) {
case NV_MOSAIC_TOPO_1x2_BASIC: std::cout << "1x2"; break;
case NV_MOSAIC_TOPO_2x1_BASIC: std::cout << "2x1"; break;
case NV_MOSAIC_TOPO_1x3_BASIC: std::cout << "1x3"; break;
case NV_MOSAIC_TOPO_3x1_BASIC: std::cout << "3x1"; break;
case NV_MOSAIC_TOPO_1x4_BASIC: std::cout << "1x4"; break;
case NV_MOSAIC_TOPO_4x1_BASIC: std::cout << "4x1"; break;
case NV_MOSAIC_TOPO_2x2_BASIC: std::cout << "2x2"; break;
case NV_MOSAIC_TOPO_2x3_BASIC: std::cout << "2x3"; break;
case NV_MOSAIC_TOPO_2x4_BASIC: std::cout << "2x4"; break;
case NV_MOSAIC_TOPO_3x2_BASIC: std::cout << "3x2"; break;
case NV_MOSAIC_TOPO_4x2_BASIC: std::cout << "4x2"; break;
case NV_MOSAIC_TOPO_1x5_BASIC: std::cout << "1x5"; break;
case NV_MOSAIC_TOPO_1x6_BASIC: std::cout << "1x6"; break;
case NV_MOSAIC_TOPO_7x1_BASIC: std::cout << "1x7"; break;
case NV_MOSAIC_TOPO_1x2_PASSIVE_STEREO: std::cout << "1x2 passive stereo"; break;
case NV_MOSAIC_TOPO_2x1_PASSIVE_STEREO: std::cout << "2x1 passive stereo"; break;
case NV_MOSAIC_TOPO_1x3_PASSIVE_STEREO: std::cout << "1x3 passive stereo"; break;
case NV_MOSAIC_TOPO_3x1_PASSIVE_STEREO: std::cout << "3x1 passive stereo"; break;
case NV_MOSAIC_TOPO_1x4_PASSIVE_STEREO: std::cout << "1x4 passive stereo"; break;
case NV_MOSAIC_TOPO_4x1_PASSIVE_STEREO: std::cout << "4x1 passive stereo"; break;
case NV_MOSAIC_TOPO_2x2_PASSIVE_STEREO: std::cout << "2x2 passive stereo"; break;
default: std::cout << "unknown topology"; break;
}
std::cout << std::endl;
}
else if (mosaic_topology.isPossible) {
std::cout << "Mosaic is DISABLED but supported" << std::endl;
}
//------------------------------------------------------------------------------
// Show current display grid (mosaic) configuration, including where mosaic is
// disabled and each display is a 1x1 grid.
if (mosaic_topology.isPossible) {
NvU32 num_grids = 0;
if (NvAPI_Mosaic_EnumDisplayGrids(nullptr, &num_grids) != NVAPI_OK) {
std::cerr << "Error: Failed to enumerate display grids!" << std::endl;
return EXIT_FAILURE;
}
std::vector<NV_MOSAIC_GRID_TOPO> display_grids(num_grids);
std::for_each(begin(display_grids), end(display_grids), [](NV_MOSAIC_GRID_TOPO& display_grid) {
display_grid.version = NV_MOSAIC_GRID_TOPO_VER;
});
if (NvAPI_Mosaic_EnumDisplayGrids(display_grids.data(), &num_grids) != NVAPI_OK) {
std::cerr << "Error: Failed to enumerate display grids!" << std::endl;
return EXIT_FAILURE;
}
assert(display_grids.size() >= num_grids); // In some cases the initially reported number appears to be conservative!
display_grids.resize(num_grids);
std::for_each(begin(display_grids), end(display_grids), [](NV_MOSAIC_GRID_TOPO& display_grid) {
print_to_stream(std::cout, display_grid, " ");
});
}
//------------------------------------------------------------------------------
// Enumerate logical GPUs and the physical GPUs underneath it.
NvLogicalGpuHandle logical_gpus[NVAPI_MAX_LOGICAL_GPUS] = {};
NvU32 num_logical_gpus = 0;
if (NvAPI_EnumLogicalGPUs(logical_gpus, &num_logical_gpus) != NVAPI_OK) {
std::cerr << "Error: Failed to enumerate logical GPUs!" << std::endl;
return EXIT_FAILURE;
}
NvPhysicalGpuHandle physical_gpus[NVAPI_MAX_PHYSICAL_GPUS] = { 0 };
NvU32 num_physical_gpus = 0;
NvU32 total_num_physical_gpus = 0;
for (NvU32 logical_gpu_index = 0; logical_gpu_index < num_logical_gpus; ++logical_gpu_index) {
std::cout << "Logical GPU " << logical_gpu_index << std::endl;
if (NvAPI_GetPhysicalGPUsFromLogicalGPU(logical_gpus[logical_gpu_index], physical_gpus, &num_physical_gpus) != NVAPI_OK) {
std::cerr << "Error: Failed to enumerate physical GPUs!" << std::endl;
continue;
}
total_num_physical_gpus += num_physical_gpus;
for (size_t physical_gpu_index = 0; physical_gpu_index < num_physical_gpus; ++physical_gpu_index) {
NvAPI_ShortString name = {};
if (NvAPI_GPU_GetFullName(physical_gpus[physical_gpu_index], name) != NVAPI_OK) {
std::cerr << "Error: Failed to get GPU name!" << std::endl;
continue;
}
std::cout << " Physical GPU " << physical_gpu_index << ": " << name << std::endl;
NvU32 num_displays = 0;
if (NvAPI_GPU_GetAllDisplayIds(physical_gpus[physical_gpu_index], nullptr, &num_displays) != NVAPI_OK) {
std::cerr << "Error: Failed to get conencted displays!" << std::endl;
continue;
}
std::vector<NV_GPU_DISPLAYIDS> displays(num_displays);
std::for_each(begin(displays), end(displays), [](NV_GPU_DISPLAYIDS& display) {
display.version = NV_GPU_DISPLAYIDS_VER;
});
if (NvAPI_GPU_GetAllDisplayIds(physical_gpus[physical_gpu_index], displays.data(), &num_displays) != NVAPI_OK) {
std::cerr << "Error: Failed to get conencted displays!" << std::endl;
continue;
}
assert(displays.size() >= num_displays); // In some cases the initially reported number appears to be conservative!
displays.resize(num_displays);
for (size_t display_index = 0; display_index < displays.size(); ++display_index) {
std::cout << " Display " << display_index << ": ";
switch (displays[display_index].connectorType) {
case NV_MONITOR_CONN_TYPE_VGA: std::cout << "VGA"; break;
case NV_MONITOR_CONN_TYPE_COMPONENT: std::cout << "Component"; break;
case NV_MONITOR_CONN_TYPE_SVIDEO: std::cout << "S-Video"; break;
case NV_MONITOR_CONN_TYPE_HDMI: std::cout << "HDMI"; break;
case NV_MONITOR_CONN_TYPE_DVI: std::cout << "DVI"; break;
case NV_MONITOR_CONN_TYPE_LVDS: std::cout << "LVDS"; break;
case NV_MONITOR_CONN_TYPE_DP: std::cout << "DP"; break;
case NV_MONITOR_CONN_TYPE_COMPOSITE: std::cout << "Composite"; break;
default: std::cout << "Unknown"; break;
}
std::cout << ", 0x" << std::hex << std::setfill('0') << std::setw(8) << displays[display_index].displayId << std::dec;
if (displays[display_index].isDynamic) {
std::cout << ", dynamic";
}
if (displays[display_index].isActive) {
std::cout << ", active";
}
if (displays[display_index].isCluster) {
std::cout << ", cluster";
}
if (displays[display_index].isOSVisible) {
std::cout << ", OS visible";
}
if (displays[display_index].isWFD) {
std::cout << ", wireless";
}
if (displays[display_index].isConnected) {
if (displays[display_index].isPhysicallyConnected) {
std::cout << ", physically connected";
}
else {
std::cout << ", connected";
}
}
std::cout << std::endl;
}
}
}
if (NvAPI_EnumPhysicalGPUs(physical_gpus, &num_physical_gpus) != NVAPI_OK) {
std::cerr << "Error: Failed to enumerate physical GPUs!" << std::endl;
return EXIT_FAILURE;
}
assert(num_physical_gpus == total_num_physical_gpus);
//------------------------------------------------------------------------------
// ...
return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
// DirectX based GPU query
//------------------------------------------------------------------------------
int directx()
{
std::cout << "[DirectX]" << std::endl;
//------------------------------------------------------------------------------
// Grab DirectX factory.
ComPtr<IDXGIFactory4> factory;
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) {
std::cerr << "Error: Failed to create DXGI factory!" << std::endl;
return EXIT_FAILURE;
}
//------------------------------------------------------------------------------
// Enumerate DirectX adapters (GPUs).
std::cout << std::endl;
UINT adapter_index = 0;
IDXGIAdapter* adapter = nullptr;
while (factory->EnumAdapters(adapter_index, &adapter) != DXGI_ERROR_NOT_FOUND) {
DXGI_ADAPTER_DESC adapter_desc = {};
if (FAILED(adapter->GetDesc(&adapter_desc))) {
std::cerr << "Error: Failed to get adapter description!" << std::endl;
continue;
}
std::cout << "Adapter " << adapter_index << ": ";
std::wcout << adapter_desc.Description;
std::cout << ", 0x" << std::hex << adapter_desc.AdapterLuid.HighPart << std::setfill('0') << std::setw(8) << adapter_desc.AdapterLuid.LowPart << std::dec;
std::cout << std::endl;
UINT output_index = 0;
IDXGIOutput* output = nullptr;
//------------------------------------------------------------------------------
// Enumerate outputs (displays).
while (adapter->EnumOutputs(output_index, &output) != DXGI_ERROR_NOT_FOUND) {
DXGI_OUTPUT_DESC output_desc = {};
if (FAILED(output->GetDesc(&output_desc))) {
std::cerr << "Error: Failed to get output description!" << std::endl;
continue;
}
std::cout << " Output " << output_index << ": ";
std::wcout << output_desc.DeviceName;
bool first = true;
if (output_desc.AttachedToDesktop) {
if (first) { std::cout << " ("; }
else { std::cout << ", "; }
std::cout << "display attached";
first = false;
}
MONITORINFO monitor_info = {};
monitor_info.cbSize = sizeof(monitor_info);
if (GetMonitorInfo(output_desc.Monitor, &monitor_info)) {
if (monitor_info.dwFlags & MONITORINFOF_PRIMARY) {
if (first) { std::cout << " ("; }
else { std::cout << ", "; }
std::cout << "primary display";
first = false;
}
}
if (!first) { std::cout << ")"; }
std::cout << std::endl;
output->Release();
++output_index;
}
adapter->Release();
++adapter_index;
}
return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
// OpenGL based GPU query
//------------------------------------------------------------------------------
int opengl()
{
std::cout << "[OpenGL]" << std::endl;
//------------------------------------------------------------------------------
// Check prerequisites.
if (virtual_screen_monitors.empty()) {
std::cerr << "Error: No monitors are listed for the virtual screen!" << std::endl;
return EXIT_FAILURE;
}
//------------------------------------------------------------------------------
// Initialize CUDA if available;
if (cuInit(0) == CUDA_SUCCESS) {
std::cout << std::endl << "CUDA available" << std::endl;
}
//------------------------------------------------------------------------------
// Register a window class.
WNDCLASSA wc = {};
{
wc.style = CS_OWNDC;
wc.lpfnWndProc = window_callback;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = NULL;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "TestMultiGpuMultiMonitor";
}
RegisterClassA(&wc);
//------------------------------------------------------------------------------
// Create one 'full screen' window per each monitor in the virtual screen.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// "An OpenGL window should be created with the WS_CLIPCHILDREN and
// WS_CLIPSIBLINGS styles. Additionally, the window class attribute should NOT
// include the CS_PARENTDC style." [SetPixelFormat documentation]
const DWORD style = (WS_OVERLAPPED | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
PIXELFORMATDESCRIPTOR pixel_format_desc = {};
{
pixel_format_desc.nSize = sizeof(pixel_format_desc);
pixel_format_desc.nVersion = 1;
//------------------------------------------------------------------------------
// "PFD_DEPTH_DONTCARE: To select a pixel format without a depth buffer, you
// must specify this flag. The requested pixel format can be with or without a
// depth buffer. Otherwise, only pixel formats with a depth buffer are
// considered." [PIXELFORMATDESCRIPTOR documentation]
pixel_format_desc.dwFlags = (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DEPTH_DONTCARE);
//------------------------------------------------------------------------------
// "For RGBA pixel types, it is the size of the color buffer, excluding the
// alpha bitplanes." [PIXELFORMATDESCRIPTOR documentation]
pixel_format_desc.iPixelType = PFD_TYPE_RGBA;
pixel_format_desc.cColorBits = 24;
};
std::vector<HWND> windows;
std::vector<HDC> display_contexts;
std::vector<HGLRC> gl_contexts;
for (size_t virtual_screen_monitor_index = 0; virtual_screen_monitor_index < virtual_screen_monitors.size(); ++virtual_screen_monitor_index) {
//------------------------------------------------------------------------------
// Create a 'full screen' window.
RECT window_rect = {};
{
SetRect(&window_rect,
virtual_screen_monitors[virtual_screen_monitor_index].m_x,
virtual_screen_monitors[virtual_screen_monitor_index].m_y,
(virtual_screen_monitors[virtual_screen_monitor_index].m_x + virtual_screen_monitors[virtual_screen_monitor_index].m_width),
(virtual_screen_monitors[virtual_screen_monitor_index].m_y + virtual_screen_monitors[virtual_screen_monitor_index].m_height));
AdjustWindowRect(&window_rect, style, FALSE);
}
const HWND window = CreateWindowA(wc.lpszClassName, "TestMultiGpuMultiMonitor",
style, window_rect.left, window_rect.top, (window_rect.right - window_rect.left), (window_rect.bottom - window_rect.top),
nullptr, nullptr, nullptr, nullptr);
ShowWindow(window, SW_SHOWDEFAULT);
UpdateWindow(window);
//------------------------------------------------------------------------------
// Setup the display context.
const HDC display_context = GetDC(window);
size_t num_monitors = 0;
if (EnumDisplayMonitors(display_context, nullptr, [](HMONITOR monitor, HDC display_context, LPRECT virtual_screen_rect, LPARAM user_data) {
size_t* const num_monitors_ptr = (size_t*)user_data;
(*num_monitors_ptr) += 1;
return TRUE;
}, (LPARAM)&num_monitors) == 0)
{
std::cerr << "Error: Failed to enumerate monitors for display context!" << std::endl;
return EXIT_FAILURE;
}
if (num_monitors != 1) {
std::cerr << "Error: Display context intersects more than one monitor!" << std::endl;
return EXIT_FAILURE;
}
const int pixel_format = ChoosePixelFormat(display_context, &pixel_format_desc);
if (pixel_format == 0) {
std::cerr << "Error: Failed to choose pixel format!" << std::endl;
return EXIT_FAILURE;
}
if (SetPixelFormat(display_context, pixel_format, &pixel_format_desc) != TRUE) {
std::cerr << "Error: Failed to set pixel format!" << std::endl;
return EXIT_FAILURE;
}
//------------------------------------------------------------------------------
// Ccreate OpenGL context and share lists between all the contexts.
const HGLRC gl_context = wglCreateContext(display_context);
if (gl_context == NULL) {
std::cerr << "Error: Failed to create OpenGL context!" << std::endl;
return EXIT_FAILURE;
}