-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplmctrl.cpp
More file actions
1568 lines (1278 loc) · 46.3 KB
/
plmctrl.cpp
File metadata and controls
1568 lines (1278 loc) · 46.3 KB
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
/*
* PLMCtrl - Phase-only Light Modulator Control Library
* Structured Light Lab
* Version: 0.6.0 beta
* Date: 8/Jun/2025
* Repository : https://github.com/structuredlightlab/plmctrl
*
* plmctrl is an open-source library for controlling the 0.67" Texas Instruments
* Phase-only Light Modulator (DLP6750 EVM). The library facilitates the creation, bitpacking, and
* display of holograms on the PLM, ensuring precise frame pacing during hologram sequence display.
* If you use plmctrl in your research, please cite:
*
@article{rocha2024plm,
author = {Jos\'{e} C. A. Rocha and Terry Wright and Un\.{e} G. B\={u}tait\.{e} and Joel Carpenter and George S. D. Gordon and David B. Phillips},
journal = {Opt. Express},
number = {24},
pages = {43300--43314},
publisher = {Optica Publishing Group},
title = {Fast and light-efficient wavefront shaping with a MEMS phase-only light modulator},
volume = {32},
month = {Nov},
year = {2024},
url = {https://opg.optica.org/oe/abstract.cfm?URI=oe-32-24-43300}
}
*
* External Dependencies:
* - DirectX 11: Graphics API for rendering
* - Dear ImGui: GUI handling and graphics API wrapping
* - hidapi: USB communication with the PLM
*/
// To be defined if compiled as an executable
// #define PLM_DEBUG
#include "imgui/imgui.h"
#include "imgui/imgui_impl_win32.h"
#include "imgui/imgui_impl_dx11.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <tchar.h>
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files
//#include <windows.h>
#include <stdio.h>
#include <thread>
#include <mutex>
#include <vector>
#include <chrono>
#include <cmath>
#include <iostream>
#include "PLM/PLM.h"
#include "plmctrl.h"
#include "helpers.h"
// DirectX Stuff
static ID3D11Device* g_pd3dDevice = nullptr;
static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static bool g_SwapChainOccluded = false;
static UINT g_ResizeWidth = 0, g_ResizeHeight = 0;
static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
ID3D11Texture2D* pTexture = nullptr;
ID3D11ShaderResourceView* data_texture_srv = nullptr;
D3D11_TEXTURE2D_DESC desc = {};
// Bitpack Compute Shader declarations
static ID3D11ComputeShader* g_pComputeShader = nullptr;
static ID3D11Buffer* g_pConstantBuffer = nullptr;
static ID3D11Buffer* g_pPhaseBuffer = nullptr;
static ID3D11Buffer* g_pLUTBuffer = nullptr;
static ID3D11Buffer* g_pPhaseMapBuffer = nullptr;
static ID3D11ShaderResourceView* g_pPhaseSRV = nullptr;
static ID3D11ShaderResourceView* g_pLUTSRV = nullptr;
static ID3D11ShaderResourceView* g_pPhaseMapSRV = nullptr;
static ID3D11Buffer* g_pHologramBuffer = nullptr;
static ID3D11UnorderedAccessView* g_pHologramUAV = nullptr;
ID3D11Texture2D* pHologramTexture = nullptr;
ID3D11Texture2D* pStagingTexture;
// 16 bytes
struct c_Params {
uint32_t N;
uint32_t M;
uint32_t num_holograms;
uint32_t pad;
};
bool running = false;
bool isSetupDone = false;
uint8_t* plm_image_ptr = nullptr;
std::mutex mutex;
std::mutex plm_image_mutex;
std::mutex plm_reading_status;
int N = 200, M = 200, monitor_id = 0;
int window_x0 = 0, window_y0 = 0;
int delay = 200;
enum PLM_MODE {
PLM_IDLE = 0,
PLM_PLAYING = 1,
PLM_CONTINUOUS = 2
};
PLM_MODE plm_mode = PLM_IDLE;
bool plm_connected = false;
bool plm_monitoring_status = false;
bool first_frame_trigger = false;
bool start_playing_trigger = false;
bool plm_is_displaying = false;
bool sequence_active = false;
bool displaying_active = false;
bool continuous_mode = false;
std::atomic<bool> pause_UI = false;
std::atomic<bool> bitpacking_in_progress = false;
std::atomic<bool> UI_is_rendering = false;
int frames_to_play = 0;
int frames_in_sequence = -1;
int64_t frame_index = 0;
int64_t buffer_index = -1;
long long t0 = 0;
bool camera_trigger = false;
bool show_debug_window = true;
RECT monitorRect;
std::chrono::duration<double> elapsed_content;
std::chrono::duration<double> elapsed_buffer;
std::chrono::duration<double> elapsed_total;
uint64_t MAX_FRAMES = 64;
bool windowed = false;
std::vector<unsigned char> frame;
std::vector<uint8_t> frame_set;
std::vector<uint64_t> frame_order;
std::mutex dx_mutex;
// TI's default lookup-table
float phases[17] = { 0, 0.0100, 0.0205, 0.0422, 0.0560, 0.0727, 0.1131, 0.1734, 0.3426, 0.3707, 0.4228, 0.4916, 0.5994, 0.6671, 0.7970, 0.9375, 1.0 };
// Binary counting phase-map, has to be calibrated.
int phase_map[] = {
0, 0, 0, 0,
1, 0, 0, 0,
0, 1, 0, 0,
1, 1, 0, 0,
0, 0, 1, 0,
1, 0, 1, 0,
0, 1, 1, 0,
1, 1, 1, 0,
0, 0, 0, 1,
1, 0, 0, 1,
0, 1, 0, 1,
1, 1, 0, 1,
0, 0, 1, 1,
1, 0, 1, 1,
0, 1, 1, 1,
1, 1, 1, 1
};
std::thread ui_thread;
std::thread plm_status_thread;
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
void DebugWindow(bool show, ImGuiIO& io);
bool CompileComputeShader(ID3D11Device* device)
{
ID3DBlob* pBlob = nullptr;
ID3DBlob* pErrorBlob = nullptr;
HRESULT hr = D3DCompileFromFile(
L"BitpackHologramsCS.hlsl",
nullptr,
nullptr,
"main",
"cs_5_0",
0,
0,
&pBlob,
&pErrorBlob
);
if (FAILED(hr))
{
if (pErrorBlob)
{
// Print the error message to stderr
std::cerr << "Compute Shader Compilation Error: "
<< (char*)pErrorBlob->GetBufferPointer() << std::endl;
pErrorBlob->Release();
}
if (pBlob) pBlob->Release();
return false;
}
hr = device->CreateComputeShader(
pBlob->GetBufferPointer(),
pBlob->GetBufferSize(),
nullptr,
&g_pComputeShader
);
if (pBlob->GetBufferSize() == 0)
{
std::cerr << "Shader blob size is 0" << std::endl;
pBlob->Release();
return false;
}
pBlob->Release();
if (FAILED(hr))
{
std::cerr << "CreateComputeShader failed with HRESULT: 0x" << std::hex << hr << std::dec << std::endl;
return false;
}
return true;
};
bool InitBitpackResources()
{
if (!g_pd3dDevice) return false;
HRESULT hr;
D3D11_BUFFER_DESC bufDesc = {};
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
// Constant buffer for shader parameters
bufDesc = {};
bufDesc.ByteWidth = sizeof(c_Params);
bufDesc.Usage = D3D11_USAGE_DEFAULT;
bufDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
hr = g_pd3dDevice->CreateBuffer(&bufDesc, nullptr, &g_pConstantBuffer);
if (FAILED(hr)) return false;
// Phase buffer for input data, sized for max 24 holograms
const int max_num_holograms = 24;
bufDesc = {};
bufDesc.ByteWidth = sizeof(float) * N * M * max_num_holograms;
bufDesc.Usage = D3D11_USAGE_DYNAMIC;
bufDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
bufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
bufDesc.StructureByteStride = sizeof(float);
hr = g_pd3dDevice->CreateBuffer(&bufDesc, nullptr, &g_pPhaseBuffer);
if (FAILED(hr)) {
g_pConstantBuffer->Release();
g_pConstantBuffer = nullptr;
return false;
}
srvDesc = {};
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
srvDesc.BufferEx.FirstElement = 0;
srvDesc.BufferEx.NumElements = N * M * max_num_holograms;
hr = g_pd3dDevice->CreateShaderResourceView(g_pPhaseBuffer, &srvDesc, &g_pPhaseSRV);
if (FAILED(hr)) {
g_pPhaseBuffer->Release();
g_pPhaseBuffer = nullptr;
g_pConstantBuffer->Release();
g_pConstantBuffer = nullptr;
return false;
}
//////////////
bufDesc = {};
bufDesc.ByteWidth = sizeof(float) * 17;
bufDesc.Usage = D3D11_USAGE_DEFAULT;
bufDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
bufDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
bufDesc.StructureByteStride = sizeof(float);
hr = g_pd3dDevice->CreateBuffer(&bufDesc, nullptr, &g_pLUTBuffer);
srvDesc = {};
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
srvDesc.BufferEx.FirstElement = 0;
srvDesc.BufferEx.NumElements = 17;
hr = g_pd3dDevice->CreateShaderResourceView(g_pLUTBuffer, &srvDesc, &g_pLUTSRV);
//////////////
bufDesc = {};
bufDesc.ByteWidth = sizeof(int) * 64;
bufDesc.Usage = D3D11_USAGE_DEFAULT;
bufDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
bufDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
bufDesc.StructureByteStride = sizeof(int);
hr = g_pd3dDevice->CreateBuffer(&bufDesc, nullptr, &g_pPhaseMapBuffer);
srvDesc = {};
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
srvDesc.BufferEx.FirstElement = 0;
srvDesc.BufferEx.NumElements = 64;
hr = g_pd3dDevice->CreateShaderResourceView(g_pPhaseMapBuffer, &srvDesc, &g_pPhaseMapSRV);
// Hologram buffer for output (corrected to match output size)
D3D11_TEXTURE2D_DESC texDesc = {};
texDesc.Width = 2 * N;
texDesc.Height = 2 * M;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R32_UINT;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
hr = g_pd3dDevice->CreateTexture2D(&texDesc, nullptr, &pHologramTexture);
if (FAILED(hr)) {
std::cout << "Failed to create hologram buffer with HRESULT: 0x"
<< std::hex << hr << std::dec << std::endl;
g_pPhaseSRV->Release();
g_pPhaseSRV = nullptr;
g_pPhaseBuffer->Release();
g_pPhaseBuffer = nullptr;
g_pConstantBuffer->Release();
g_pConstantBuffer = nullptr;
return false;
}
D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
uavDesc.Format = DXGI_FORMAT_R32_UINT;
uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
uavDesc.Texture2D.MipSlice = 0;
hr = g_pd3dDevice->CreateUnorderedAccessView(pHologramTexture, &uavDesc, &g_pHologramUAV);
if (FAILED(hr)) {
std::cout << "Failed to create UAV with HRESULT: 0x"
<< std::hex << hr << std::dec << std::endl;
pHologramTexture->Release();
pHologramTexture = nullptr;
g_pPhaseSRV->Release();
g_pPhaseSRV = nullptr;
g_pPhaseBuffer->Release();
g_pPhaseBuffer = nullptr;
g_pConstantBuffer->Release();
g_pConstantBuffer = nullptr;
return false;
}
// Staging buffer to copy output to CPU
D3D11_TEXTURE2D_DESC stagingDesc = texDesc;
//stagingDesc.Width = 4*2*N;
//stagingDesc.Height = 2*M;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
hr = g_pd3dDevice->CreateTexture2D(&stagingDesc, nullptr, &pStagingTexture);
if (FAILED(hr)) {
g_pHologramUAV->Release();
g_pHologramUAV = nullptr;
pHologramTexture->Release();
pHologramTexture = nullptr;
g_pPhaseSRV->Release();
g_pPhaseSRV = nullptr;
g_pPhaseBuffer->Release();
g_pPhaseBuffer = nullptr;
g_pConstantBuffer->Release();
g_pConstantBuffer = nullptr;
return false;
}
return true;
}
bool Cleanup() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
StopUI();
return true;
};
int Play() {return PLM::Play();};
int Stop() {return PLM::Stop();};
int SetSource(unsigned int source, unsigned int port_width) {return PLM::SetSource(source, port_width);};
int SetPortSwap(unsigned int port, unsigned int swap) {return PLM::SetPortSwap(port, swap);};
int SetPortConfig(int connection_type) {
//HDMI = 1, DP = 2
if (connection_type != 1 && connection_type != 2) return -1;
return PLM::SetPortConfig(connection_type == 1 ? 0 : 2, 0, 0, 0);
};
int SetConnectionType(int connection_type) {return PLM::SetConnectionType(connection_type);};
int SetVideoPatternMode() {return PLM::SetVideoPatternMode();};
int UpdateLUT(int play_mode, int connection_type) {return PLM::UpdateLUT(play_mode, connection_type);};
int GetVideoPatternMode() {return PLM::GetVideoPatternMode();};
int GetConnectionType() {return PLM::GetConnectionType();};
int Open() {return PLM::Open();};
int Close() {return PLM::Close();};
//int Configure(unsigned int play_mode, unsigned int connection_type) {
// return PLM::Configure(play_mode, connection_type);
//}
bool PauseUI() {
pause_UI = true;
return true;
};
bool ResumeUI() {
pause_UI = false;
return true;
};
bool StartSequence(int number_of_frames) {
if (number_of_frames > MAX_FRAMES) {
return false;
};
frames_to_play = number_of_frames;
frames_in_sequence = number_of_frames;
sequence_active = true;
first_frame_trigger = true;
return true;
}
bool StartDisplaying() {
// Start displaying continuously on the PLM
// Tailored for real-time applications.
// IN CONSTRUCTION
displaying_active = true;
first_frame_trigger = true;
return true;
}
bool Resynchronise(unsigned long long offset) {
// IN CONSTRUCTION
return true;
}
// Main code
int UI(){
//if (!GetSecondMonitorRect(monitorRect, monitor_id)) {
// std::cerr << "Second monitor not found!" << std::endl;
// return 1;
//}
WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"plmctrl", nullptr };
::RegisterClassExW(&wc);
monitorRect.left = 0;
monitorRect.top = 0;
HWND hwnd = ::CreateWindowEx(
WS_EX_TOPMOST, // dwExStyle: No extended styles
wc.lpszClassName,
L"plmctrl",
WS_POPUP | WS_VISIBLE,
window_x0, window_y0,
2*N, 2*M,
nullptr,
nullptr,
wc.hInstance,
nullptr
);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClassW(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOW);
::UpdateWindow(hwnd);
//SetWindowLong(hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
//SetWindowPos(hwnd, HWND_TOP,
// monitorRect.left, monitorRect.top,
// monitorRect.right - monitorRect.left, monitorRect.bottom - monitorRect.top, SWP_FRAMECHANGED);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
//io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigDockingWithShift = true; // Enable docking with shift key
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) std::cout << "[plmctrl]: Viewports enabled" << std::endl;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
ImGuiMouseButton LMB = ImGuiMouseButton_Left;
static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs
| ImGuiTabBarFlags_Reorderable
| ImGuiTabBarFlags_FittingPolicyResizeDown;
using timepoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
timepoint start_total;
timepoint end_total;
timepoint start;
timepoint end;
// Frame texture (holds the bitpacked holograms)
desc.Width = 2 * N;
desc.Height = 2 * M;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
g_pd3dDevice->CreateTexture2D(&desc, nullptr, &pTexture);
g_pd3dDevice->CreateShaderResourceView(pTexture, nullptr, &data_texture_srv);
D3D11_SAMPLER_DESC samplerDesc = {};
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; // Nearest neighbor (no interpolation)
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
ID3D11SamplerState* pSamplerState = nullptr;
g_pd3dDevice->CreateSamplerState(&samplerDesc, &pSamplerState);
timepoint now;
bool done = false;
// Main UI loop. Changes the frames with VSync enabled
while (running && !done)
{
UI_is_rendering.store(false);
if (bitpacking_in_progress.load() || pause_UI.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
};
UI_is_rendering.store(true);
if (frames_to_play < 0 && sequence_active) {
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
// Pause Playing the sequence.
if (plm_connected) PLM::Stop(); // This only works with INCLUDE_LIGHTCRAFTER_WRAPPERS is defined
plm_is_displaying = false;
sequence_active = false;
buffer_index = -1; // buffer_index = -1 signals that the sequence has ended
plm_mode = PLM_IDLE;
camera_trigger = false;
//std::cout << "Sequence finished" << std::endl;
};
start_total = std::chrono::high_resolution_clock::now();
start = std::chrono::high_resolution_clock::now();
static ImVec2 mouse_pos, image_pos, image_size;
// Poll and handle messages (inputs, window resize, etc.)
// See the WndProc() function below for our to dispatch events to the Win32 backend.
MSG msg;
while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
//std::cout << msg.message << std::endl;
if (msg.message == WM_QUIT)
done = true;
};
if (done)
break;
// Handle window being minimized or screen locked
if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED){
::Sleep(10);
continue;
}
g_SwapChainOccluded = false;
// Handle window resize (we don't resize directly in the WM_SIZE handler)
if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
{
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, g_ResizeWidth, g_ResizeHeight, DXGI_FORMAT_UNKNOWN, 0);
g_ResizeWidth = g_ResizeHeight = 0;
CreateRenderTarget();
}
// Start the Dear ImGui frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
static bool show_demo_window = false;
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
const ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
static ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(viewport->WorkSize);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
bool popen = true;
ImGui::Begin("DockSpace", &popen, window_flags);
ImGui::PopStyleVar(2);
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
ImGui::End();
static uint64_t frame_elements = 4 * (2 * N) * (2 * M);
if (frames_to_play == frames_in_sequence && sequence_active) {
plm_mode = PLM_PLAYING;
frame_index = 0;
first_frame_trigger = false;
start_playing_trigger = true;
}
plm_image_ptr = frame_set.data()
+ frame_order[frame_index % MAX_FRAMES] * frame_elements;
// PLM frame window
PLM::ImagescPLM("PLM", plm_image_ptr, data_texture_srv, g_pd3dDevice, g_pd3dDeviceContext, pSamplerState, io, 2 * N, 2 * M, &mutex, window_x0, window_y0);
DebugWindow(show_debug_window, io);
// ImGui Rendering
ImGui::Render();
const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
};
int display_w, display_h;
// Present with VSync. This is the most important part for correct frame-pace
HRESULT hr = g_pSwapChain->Present(1, 0);
g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED);
end = std::chrono::high_resolution_clock::now();
elapsed_content = end - start;
start = std::chrono::high_resolution_clock::now();
buffer_index = camera_trigger ? buffer_index + 1 : -1;
if (plm_mode == PLM_PLAYING && frames_to_play == frames_in_sequence) {
camera_trigger = true;
buffer_index = 0;
t0 = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
//std::cout << "[plmctrl]: First frame trigger" << std::endl;
PLM::Play(); // This only works if LightCrafter wrappers are included
};
//if (plm_mode == PLM_PLAYING) {
// std::cout << "[plmctrl]: Buffer Index on plmctrl: " << buffer_index << std::endl;
//}
end = std::chrono::high_resolution_clock::now();
elapsed_buffer = end - start;
end_total = std::chrono::high_resolution_clock::now();
elapsed_total = end_total - start_total;
// first_frame_trigger is a variable to know exactly that the first frame was already sent to the GPU buffer queue.
if (frames_to_play >= 0 && !(first_frame_trigger)) {
frame_index++;
frame_index = clamp(frame_index, 0, MAX_FRAMES - 1);
frames_to_play--;
};
UI_is_rendering.store(false);
};
// Cleanup
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClassW(wc.lpszClassName, wc.hInstance);
if (running) {
std::thread cleanup_thread(Cleanup);
cleanup_thread.detach();
};
return 0;
}
void StartUI(unsigned int number_of_frames) {
MAX_FRAMES = number_of_frames;
frame_order.resize(MAX_FRAMES);
for (int i = 0; i < MAX_FRAMES; i++) {
frame_order[i] = i;
};
if (running) {
StopUI();
StartUI(number_of_frames);
return;
};
running = true;
plm_image_ptr = nullptr;
frame.resize(4 * (2 * N) * (2 * M));
frame_set.resize(4 * (2 * N) * (2 * M) * MAX_FRAMES);
std::fill(frame_set.begin(), frame_set.end(), 255);
#ifndef PLM_DEBUG
std::cout << "Starting UI thread" << std::endl;
ui_thread = std::thread(UI);
#else
UI();
#endif
return;
}
void ResetUI() {
running = false;
StopUI();
StartUI(MAX_FRAMES);
}
void StopUI() {
isSetupDone = false;
running = false;
plm_image_ptr = nullptr;
ui_thread.join();
if (plm_connected) {
//USB_Close(); // THIS ONLY WORKS IN THE plmctrl's dev branch
plm_connected = false;
};
return;
}
void SetWindowed(bool windowed_mode) {
windowed = windowed_mode;
};
void SetPLMWindowPos(int width, int height, int x0 = 0, int y0 = 0 ) {
N = width;
M = height;
window_x0 = x0;
window_y0 = y0;
};
void SetLookupTable(float* lut) {
for (int i = 0; i < 17; i++) {
phases[i] = lut[i];
}
}
bool SetPhaseMap(int* new_phase_map) {
const int phase_map_size = 16 * 4;
for (int i = 0; i < phase_map_size; i++) {
phase_map[i] = new_phase_map[i];
};
return true;
}
bool SetFrameSequence(unsigned long long* sequence, unsigned long long length) {
if (length > MAX_FRAMES) {
return false;
};
for (int i = 0; i < length; i++) {
frame_order[i] = sequence[i];
};
return true;
};
bool InsertPLMFrame(unsigned char* frame, unsigned long long num_frames = 1, unsigned long long offset = 0, int type = 0) {
// Type: 0 - RGB;
// Type: 1 - RGBA;
if (offset + num_frames > MAX_FRAMES) {
// Exceeds the maximum number of frames we can store
return false;
};
//std::cout << "Inserting " << num_frames << " frames at offset " << offset << std::endl;
uint64_t rgb_elements = (2 * N) * (2 * M);
uint64_t frame_elements = 4 * rgb_elements;
uint64_t total_elements = num_frames * frame_elements;
int k = 0;
if (type == 0) {
//std::cout << "Type: RGB" << std::endl;
for (uint64_t n = 0; n < num_frames; n++) {
for (uint64_t i = 0; i < rgb_elements; i++) {
frame_set.at(4 * i + (n + offset) * frame_elements + 0) = frame[3 * i + n * (3 * rgb_elements) + 0];
frame_set.at(4 * i + (n + offset) * frame_elements + 1) = frame[3 * i + n * (3 * rgb_elements) + 1];
frame_set.at(4 * i + (n + offset) * frame_elements + 2) = frame[3 * i + n * (3 * rgb_elements) + 2];
};
//std::cout << "Frame " << n << " inserted" << std::endl;
};
}
else if (type == 1) {
//std::cout << "Type: RGBA" << std::endl;
std::copy(
frame,
frame + total_elements,
frame_set.begin() + offset * frame_elements
);
};
//std::cout << num_frames << " frames inserted" << std::endl;
return true;
};
bool SetPLMFrame(unsigned long long offset = 0) {
if (offset >= MAX_FRAMES) {
// Exceeds the maximum number of holograms we can store
return false;
};
frame_index = offset;
//for (int i = 0; i < MAX_FRAMES; i++) {
// frame_order[i] = offset;
//};
return true;
};
bool GrabPLMFrame(unsigned char* hologram, uint64_t index = 0) {
if (index >= MAX_FRAMES) {
// Exceeds the maximum number of holograms we can store
return false;
};
uint64_t frame_elements = 4 * (2 * N) * (2 * M);
uint64_t ptr_offset = index * frame_elements;
for (uint64_t i = 0; i < frame_elements; i++) {
hologram[i] = frame_set.at(i + ptr_offset);
};
return true;
};
unsigned int QuantisePhase(float phaseVal) {
for (int level_num = 0; level_num < 17; level_num++) {
if ((phaseVal >= phases[level_num]) && (phaseVal < phases[level_num + 1])) {
if (fabs(phaseVal - phases[level_num]) < fabs(phaseVal - phases[level_num + 1])) {
return level_num;
};
return (level_num + 1) % 16;
}
}
return 0; // Default return if no condition is met
}
bool BitpackHolograms(
float* phase,
unsigned char* hologram,
unsigned long long N,
unsigned long long M,
int num_holograms
) {
// Check if the number of holograms is within the limit
if (num_holograms > 24) {
return false;
};
uint64_t phase_elements = N * M;
uint64_t holo = 0;
uint64_t color_id = 0;
uint64_t offset = 0;
int level = 0;
for (int n = 0; n < num_holograms; n++) {
color_id = floor(holo % 24 / 8);
offset = holo % 8;
for (uint64_t j = 0; j < M; j++) {
for (uint64_t i = 0; i < N; i++) {
// Quantize the phase values
level = QuantisePhase(phase[i + j * N + n * phase_elements]);
// Encode the phase values into the hologram
hologram[4 * (2 * i + 0) + (2 * j + 1) * (4 * 2 * N) + color_id] |= phase_map[level * 4 + 0] << offset;
hologram[4 * (2 * i + 0) + (2 * j + 0) * (4 * 2 * N) + color_id] |= phase_map[level * 4 + 1] << offset;
hologram[4 * (2 * i + 1) + (2 * j + 1) * (4 * 2 * N) + color_id] |= phase_map[level * 4 + 2] << offset;
hologram[4 * (2 * i + 1) + (2 * j + 0) * (4 * 2 * N) + color_id] |= phase_map[level * 4 + 3] << offset;
hologram[4 * (2 * i + 0) + (2 * j + 1) * (4 * 2 * N) + 3] = 255;
hologram[4 * (2 * i + 0) + (2 * j + 0) * (4 * 2 * N) + 3] = 255;
hologram[4 * (2 * i + 1) + (2 * j + 1) * (4 * 2 * N) + 3] = 255;
hologram[4 * (2 * i + 1) + (2 * j + 0) * (4 * 2 * N) + 3] = 255;
};
};
holo++;
}
return true;
};
bool BitpackHologramsGPU(
float* phase,
unsigned char* hologram,
unsigned long long N,
unsigned long long M,
int num_holograms
)
{
// Pause the UI main loop
bitpacking_in_progress.store(true);