-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshader.cpp
More file actions
1914 lines (1740 loc) · 63.7 KB
/
shader.cpp
File metadata and controls
1914 lines (1740 loc) · 63.7 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
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <gl/GL.h>
#include <stdarg.h>
// ---------------------------------------------------------------------------
// Optional debug logging. Define AVS_LOG (here or via /DAVS_LOG on the cl
// command line) to write a timestamped trace to %TEMP%\avs_shader.log.
// Compiles away to nothing when AVS_LOG is not defined.
// ---------------------------------------------------------------------------
//#define AVS_LOG
#ifdef AVS_LOG
static HANDLE g_logHandle = INVALID_HANDLE_VALUE;
static void LogF(const char *fmt, ...)
{
if (g_logHandle == INVALID_HANDLE_VALUE)
{
char path[MAX_PATH];
const char *fname = "avs_shader.log";
int pathLen = lstrlenA(path);
int nameLen = lstrlenA(fname);
if (pathLen + nameLen + 1 >= MAX_PATH)
return;
for (int i = 0; i <= nameLen; ++i)
path[pathLen + i] = fname[i];
g_logHandle = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (g_logHandle == INVALID_HANDLE_VALUE)
return;
}
char buf[1024];
SYSTEMTIME st;
GetLocalTime(&st);
int n = wsprintfA(buf, "[%04u-%02u-%02u %02u:%02u:%02u.%03u pid=%lu] ",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
GetCurrentProcessId());
va_list ap;
va_start(ap, fmt);
int m = wvsprintfA(buf + n, fmt, ap);
va_end(ap);
if (m > 0)
n += m;
if (n < (int)sizeof(buf) - 1)
buf[n++] = '\n';
DWORD written;
WriteFile(g_logHandle, buf, (DWORD)n, &written, nullptr);
}
#define LOG(...) LogF(__VA_ARGS__)
#else
#define LOG(...) ((void)0)
#endif
// ---- WGL extension prototypes (loaded at runtime) -------------------------
typedef HGLRC(WINAPI *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *);
typedef BOOL(WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int);
typedef GLuint(WINAPI *PFNGLCREATESHADERPROC)(GLenum);
typedef void(WINAPI *PFNGLSHADERSOURCEPROC)(GLuint, GLsizei, const char **, const GLint *);
typedef void(WINAPI *PFNGLCOMPILESHADERPROC)(GLuint);
typedef GLuint(WINAPI *PFNGLCREATEPROGRAMPROC)(void);
typedef void(WINAPI *PFNGLATTACHSHADERPROC)(GLuint, GLuint);
typedef void(WINAPI *PFNGLLINKPROGRAMPROC)(GLuint);
typedef void(WINAPI *PFNGLUSEPROGRAMPROC)(GLuint);
typedef void(WINAPI *PFNGLDELETESHADERPROC)(GLuint);
typedef void(WINAPI *PFNGLDELETEPROGRAMPROC)(GLuint);
typedef GLint(WINAPI *PFNGLGETUNIFORMLOCATIONPROC)(GLuint, const char *);
typedef void(WINAPI *PFNGLUNIFORM1FPROC)(GLint, float);
typedef void(WINAPI *PFNGLUNIFORM1IPROC)(GLint, int);
typedef void(WINAPI *PFNGLUNIFORM2FPROC)(GLint, float, float);
typedef void(WINAPI *PFNGLUNIFORM3FPROC)(GLint, float, float, float);
typedef void(WINAPI *PFNGLUNIFORM4FPROC)(GLint, float, float, float, float);
typedef void(WINAPI *PFNGLUNIFORM4FVPROC)(GLint, GLsizei, const float *);
typedef void(WINAPI *PFNGLGETSHADERIVPROC)(GLuint, GLenum, GLint *);
typedef void(WINAPI *PFNGLGETSHADERINFOLOGPROC)(GLuint, GLsizei, GLsizei *, char *);
typedef void(WINAPI *PFNGLGETPROGRAMIVPROC)(GLuint, GLenum, GLint *);
typedef void(WINAPI *PFNGLGETPROGRAMINFOLOGPROC)(GLuint, GLsizei, GLsizei *, char *);
typedef void(WINAPI *PFNGLACTIVETEXTUREPROC)(GLenum);
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GL_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GL_BGRA 0x80E1
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE1 0x84C1
#define GL_CLAMP_TO_EDGE 0x812F
static PFNGLCREATESHADERPROC glCreateShader;
static PFNGLSHADERSOURCEPROC glShaderSource;
static PFNGLCOMPILESHADERPROC glCompileShader;
static PFNGLCREATEPROGRAMPROC glCreateProgram;
static PFNGLATTACHSHADERPROC glAttachShader;
static PFNGLLINKPROGRAMPROC glLinkProgram;
static PFNGLUSEPROGRAMPROC glUseProgram;
static PFNGLDELETESHADERPROC glDeleteShader;
static PFNGLDELETEPROGRAMPROC glDeleteProgram;
static PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
static PFNGLUNIFORM1FPROC glUniform1f;
static PFNGLUNIFORM1IPROC glUniform1i;
static PFNGLUNIFORM2FPROC glUniform2f;
static PFNGLUNIFORM3FPROC glUniform3f;
static PFNGLUNIFORM4FPROC glUniform4f;
static PFNGLUNIFORM4FVPROC glUniform4fv;
static PFNGLGETSHADERIVPROC glGetShaderiv;
static PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
static PFNGLGETPROGRAMIVPROC glGetProgramiv;
static PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
static PFNGLACTIVETEXTUREPROC glActiveTexture;
static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT;
#define LOAD_GL(T, name) name = (T)wglGetProcAddress(#name)
// ---------------------------------------------------------------------------
static HDC g_hdc = nullptr;
static HGLRC g_hglrc = nullptr;
static GLuint g_prog = 0;
static int g_w = 1, g_h = 1;
static DWORD g_startMs = 0;
static float g_mx = 0.5f, g_my = 0.5f;
static bool g_shaderHasClock = false; // true if shader uses iDate (has its own clock)
static bool g_lockOnExit = false; // lock workstation when shader is dismissed
static HANDLE g_hMutex = nullptr; // single-instance mutex
// ---------------------------------------------------------------------------
// Monitor dead-zone culling
// ---------------------------------------------------------------------------
#define MAX_MONITORS 8
static RECT g_monRects[MAX_MONITORS]; // Windows coords (top-left origin)
static int g_monCount = 0;
static bool g_needsCulling = false; // true if monitors differ in size/position
static bool g_primaryOnly = false; // true if shader uses iDate → confine to primary monitor
static RECT g_primaryRect = {}; // primary monitor rect (Windows coords)
static GLint g_uMonCount = -1;
static GLint g_uMonRects = -1;
static GLint g_uPrimRect = -1;
// GL-space monitor rects: vec4(xMin, yMin, xMax, yMax) with Y=0 at bottom
static float g_monGL[MAX_MONITORS * 4];
static float g_primGL[4]; // primary monitor rect in GL coords
static BOOL CALLBACK MonitorEnumProc(HMONITOR hMon, HDC, LPRECT rc, LPARAM)
{
if (g_monCount < MAX_MONITORS)
g_monRects[g_monCount++] = *rc;
MONITORINFO mi = {};
mi.cbSize = sizeof(mi);
if (GetMonitorInfoW(hMon, &mi) && (mi.dwFlags & MONITORINFOF_PRIMARY))
g_primaryRect = mi.rcMonitor;
return TRUE;
}
static void EnumerateMonitors()
{
g_monCount = 0;
EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, 0);
if (g_monCount < 2)
{
g_needsCulling = false;
return;
}
// Check if all monitors share the same height and vertical position
// If so, no dead zones exist — skip culling
bool allSame = true;
int h0 = g_monRects[0].bottom - g_monRects[0].top;
int t0 = g_monRects[0].top;
for (int i = 1; i < g_monCount; ++i)
{
int hi = g_monRects[i].bottom - g_monRects[i].top;
int ti = g_monRects[i].top;
if (hi != h0 || ti != t0)
{
allSame = false;
break;
}
}
g_needsCulling = !allSame;
}
static void BuildMonitorGLRects(int vx, int vy, int vw, int vh)
{
// Convert Windows rects to GL coords:
// GL x = winX - vx
// GL y = (vh - 1) - (winY - vy) → flip Y
for (int i = 0; i < g_monCount; ++i)
{
float xMin = (float)(g_monRects[i].left - vx);
float xMax = (float)(g_monRects[i].right - vx);
// Flip Y: Windows top→GL bottom
float yMin = (float)(vh - (g_monRects[i].bottom - vy));
float yMax = (float)(vh - (g_monRects[i].top - vy));
g_monGL[i * 4 + 0] = xMin;
g_monGL[i * 4 + 1] = yMin;
g_monGL[i * 4 + 2] = xMax;
g_monGL[i * 4 + 3] = yMax;
}
g_primGL[0] = (float)(g_primaryRect.left - vx);
g_primGL[2] = (float)(g_primaryRect.right - vx);
g_primGL[1] = (float)(vh - (g_primaryRect.bottom - vy));
g_primGL[3] = (float)(vh - (g_primaryRect.top - vy));
}
// GLSL prefix: declares uniforms and early-returns if pixel is outside all monitors
static const char *kCullPrefix = R"(
uniform int _monCount;
uniform vec4 _monRects[8];
)";
// GLSL prefix for primary-only mode (shaders that use iDate, e.g. clocks).
// Remaps gl_FragCoord into primary-monitor-local space; pixels outside are blacked out at main entry.
static const char *kPrimPrefix = R"(
uniform vec4 _primRect;
#define gl_FragCoord (gl_FragCoord - vec4(_primRect.xy, 0.0, 0.0))
)";
// Cached uniform locations (set once after link, -1 = not present)
static GLint g_uTime = -1;
static GLint g_uResolution = -1;
static GLint g_uMouse = -1;
static GLint g_uITime = -1;
static GLint g_uIResolution = -1;
static GLint g_uIMouse = -1;
static GLint g_uITimeDelta = -1;
static GLint g_uIFrame = -1;
static GLint g_uIDate = -1;
// Minimal vertex shader — just passes through a fullscreen quad
static const char *kVertSrc = R"(
void main() {
float x = float((gl_VertexID & 1) << 1) - 1.0;
float y = float((gl_VertexID & 2)) - 1.0;
gl_Position = vec4(x, y, 0.0, 1.0);
}
)";
static char *ReadFile(const char *path)
{
HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, 0, nullptr);
if (h == INVALID_HANDLE_VALUE)
return nullptr;
DWORD size = GetFileSize(h, nullptr);
char *buf = (char *)HeapAlloc(GetProcessHeap(), 0, size + 1);
DWORD rd = 0;
ReadFile(h, buf, size, &rd, nullptr);
buf[rd] = '\0';
CloseHandle(h);
return buf;
}
// ---------------------------------------------------------------------------
// Embedded shader resources
// ---------------------------------------------------------------------------
struct ResEntry
{
const char *name;
const char *data;
DWORD size;
};
static ResEntry g_mainShaders[256];
static int g_mainCount = 0;
static ResEntry g_exitShaders[64];
static int g_exitCount = 0;
// EnumResourceNamesA reuses a single internal buffer for the LPSTR name passed
// to the callback, so the pointer is only valid for the duration of that one
// callback invocation. Copy the name onto the heap before storing it.
static const char* DupResName(LPCSTR src)
{
int n = lstrlenA(src);
char* p = (char*)HeapAlloc(GetProcessHeap(), 0, (SIZE_T)n + 1);
if (!p) return nullptr;
for (int i = 0; i <= n; ++i) p[i] = src[i];
return p;
}
// Resource names starting with "exit-" (case-insensitive) are exit/fade-out
// shaders; everything else is a main screensaver shader.
static bool IsExitShaderName(LPCSTR name)
{
if (IS_INTRESOURCE(name))
return false;
char a = name[0];
if (a >= 'A' && a <= 'Z')
a = (char)(a + 32);
char b = name[1];
if (b >= 'A' && b <= 'Z')
b = (char)(b + 32);
char c = name[2];
if (c >= 'A' && c <= 'Z')
c = (char)(c + 32);
char d = name[3];
if (d >= 'A' && d <= 'Z')
d = (char)(d + 32);
char e = name[4];
return a == 'e' && b == 'x' && c == 'i' && d == 't' && e == '-';
}
static BOOL CALLBACK EnumResNameProc(HMODULE hMod, LPCSTR type, LPSTR name, LONG_PTR lParam)
{
if (IS_INTRESOURCE(name))
return TRUE;
HRSRC hr = FindResourceA(hMod, name, type);
if (!hr)
return TRUE;
HGLOBAL hg = LoadResource(hMod, hr);
if (!hg)
return TRUE;
DWORD sz = SizeofResource(hMod, hr);
const char *ptr = (const char *)LockResource(hg);
if (!ptr || sz == 0)
return TRUE;
if (IsExitShaderName(name))
{
if (g_exitCount < 64)
{
g_exitShaders[g_exitCount].name = DupResName(name);
g_exitShaders[g_exitCount].data = ptr;
g_exitShaders[g_exitCount].size = sz;
g_exitCount++;
}
}
else
{
if (g_mainCount < 256)
{
g_mainShaders[g_mainCount].name = DupResName(name);
g_mainShaders[g_mainCount].data = ptr;
g_mainShaders[g_mainCount].size = sz;
g_mainCount++;
}
}
return TRUE;
}
static void EnumerateEmbeddedShaders()
{
HMODULE hMod = GetModuleHandleA(nullptr);
EnumResourceNamesA(hMod, RT_RCDATA, EnumResNameProc, 0);
}
// xorshift32 PRNG, seeded from QPC + tick + PID for genuine entropy
static DWORD g_rngState = 0;
static DWORD XorshiftNext()
{
DWORD x = g_rngState;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
g_rngState = x ? x : 0x9E3779B9u;
return g_rngState;
}
static void SeedRng()
{
LARGE_INTEGER qpc;
QueryPerformanceCounter(&qpc);
DWORD seed = (DWORD)qpc.QuadPart ^ (DWORD)(qpc.QuadPart >> 32) ^ GetTickCount() ^ GetCurrentProcessId();
g_rngState = seed ? seed : 0xDEADBEEFu;
for (int i = 0; i < 8; ++i)
XorshiftNext();
}
// Returns heap-allocated null-terminated copy of a random embedded main shader.
static char *PickEmbeddedShader()
{
if (g_mainCount == 0)
return nullptr;
SeedRng();
int pick = (int)(XorshiftNext() % (DWORD)g_mainCount);
LOG("choosing main shader: %s (idx %d/%d)",
g_mainShaders[pick].name, pick, g_mainCount);
DWORD sz = g_mainShaders[pick].size;
char *buf = (char *)HeapAlloc(GetProcessHeap(), 0, sz + 1);
for (DWORD i = 0; i < sz; ++i)
buf[i] = g_mainShaders[pick].data[i];
buf[sz] = '\0';
return buf;
}
// Returns the chosen exit-shader resource. Index in g_exitShaders. The buffer
// returned is borrowed (points into the .exe's resource section) and is
// not heap-allocated — do not free.
static int g_exitPickedIdx = -1;
static const char *g_exitPickedSrc = nullptr;
static DWORD g_exitPickedSize = 0;
static void PickEmbeddedExitShader(int idx)
{
if (g_exitCount == 0)
return;
if (idx < 0)
idx = 0;
idx %= g_exitCount;
g_exitPickedIdx = idx;
g_exitPickedSrc = g_exitShaders[idx].data;
g_exitPickedSize = g_exitShaders[idx].size;
LOG("choosing exit shader: %s (idx %d/%d)",
g_exitShaders[idx].name, idx, g_exitCount);
}
static GLuint CompileShader(GLenum type, const char *src)
{
GLuint sh = glCreateShader(type);
glShaderSource(sh, 1, &src, nullptr);
glCompileShader(sh);
GLint ok = 0;
glGetShaderiv(sh, GL_COMPILE_STATUS, &ok);
if (!ok)
{
char log[2048];
glGetShaderInfoLog(sh, sizeof(log), nullptr, log);
MessageBoxA(nullptr, log, "Shader compile error", MB_OK | MB_ICONERROR);
}
return sh;
}
// Inject monitor culling code into fragment shader source
// Inserts uniform declarations after any #version/precision/extension lines,
// and a dead-zone check at the start of main()
static char *InjectCulling(const char *fragSrc)
{
// Find insertion point for uniforms: after last #/precision line
const char *uniformInsert = fragSrc;
const char *scan = fragSrc;
while (*scan)
{
// Skip lines starting with #, or containing "precision"
if (*scan == '#' || (scan == fragSrc || *(scan - 1) == '\n'))
{
const char *lineStart = scan;
// Check if line starts with # or "precision"
bool isDirective = (*scan == '#');
bool isPrec = (strncmp(scan, "precision", 9) == 0);
if (isDirective || isPrec)
{
// Skip to end of line
while (*scan && *scan != '\n')
scan++;
if (*scan == '\n')
scan++;
uniformInsert = scan;
continue;
}
}
// Skip to next line
while (*scan && *scan != '\n')
scan++;
if (*scan == '\n')
scan++;
break;
}
// Find "void main()" to insert the check
const char *mainPos = strstr(fragSrc, "void main()");
if (!mainPos)
mainPos = strstr(fragSrc, "void main ()");
if (!mainPos)
mainPos = strstr(fragSrc, "void main(");
if (!mainPos)
return nullptr;
// Find the opening '{' after main
const char *brace = strchr(mainPos, '{');
if (!brace)
return nullptr;
brace++; // past the '{'
const char *cullCheck = "\n"
" // Dead-zone culling: skip pixels outside all monitors\n"
" { bool _vis = false;\n"
" for (int _i = 0; _i < _monCount; _i++) {\n"
" vec4 _mr = _monRects[_i];\n"
" if (gl_FragCoord.x >= _mr.x && gl_FragCoord.x < _mr.z &&\n"
" gl_FragCoord.y >= _mr.y && gl_FragCoord.y < _mr.w)\n"
" { _vis = true; break; }\n"
" }\n"
" if (!_vis) { gl_FragColor = vec4(0,0,0,1); return; }\n"
" }\n";
int prefixLen = lstrlenA(kCullPrefix);
int checkLen = lstrlenA(cullCheck);
int srcLen = lstrlenA(fragSrc);
int outLen = srcLen + prefixLen + checkLen + 16;
char *out = (char *)HeapAlloc(GetProcessHeap(), 0, outLen);
char *w = out;
// Copy up to uniform insertion point
int uOff = (int)(uniformInsert - fragSrc);
for (int i = 0; i < uOff; ++i)
*w++ = fragSrc[i];
// Insert uniform declarations
const char *s = kCullPrefix;
while (*s)
*w++ = *s++;
// Copy from uniform insertion point up to after main's '{'
int bOff = (int)(brace - fragSrc);
for (int i = uOff; i < bOff; ++i)
*w++ = fragSrc[i];
// Insert cull check
s = cullCheck;
while (*s)
*w++ = *s++;
// Copy rest of source
const char *rest = brace;
while (*rest)
*w++ = *rest++;
*w = '\0';
return out;
}
// Inject primary-monitor-only confinement: remap gl_FragCoord and black out pixels outside primary
static char *InjectPrimaryOnly(const char *fragSrc)
{
const char *uniformInsert = fragSrc;
const char *scan = fragSrc;
while (*scan)
{
if (*scan == '#' || (scan == fragSrc || *(scan - 1) == '\n'))
{
bool isDirective = (*scan == '#');
bool isPrec = (strncmp(scan, "precision", 9) == 0);
if (isDirective || isPrec)
{
while (*scan && *scan != '\n')
scan++;
if (*scan == '\n')
scan++;
uniformInsert = scan;
continue;
}
}
while (*scan && *scan != '\n')
scan++;
if (*scan == '\n')
scan++;
break;
}
const char *mainPos = strstr(fragSrc, "void main()");
if (!mainPos)
mainPos = strstr(fragSrc, "void main ()");
if (!mainPos)
mainPos = strstr(fragSrc, "void main(");
if (!mainPos)
return nullptr;
const char *brace = strchr(mainPos, '{');
if (!brace)
return nullptr;
brace++;
// gl_FragCoord here is already remapped to primary-local by the macro.
// Out-of-primary if local coord < 0 or >= (primMax - primMin).
const char *primCheck = "\n"
" {\n"
" vec2 _sz = _primRect.zw - _primRect.xy;\n"
" if (gl_FragCoord.x < 0.0 || gl_FragCoord.x >= _sz.x ||\n"
" gl_FragCoord.y < 0.0 || gl_FragCoord.y >= _sz.y)\n"
" { gl_FragColor = vec4(0.0,0.0,0.0,1.0); return; }\n"
" }\n";
int prefixLen = lstrlenA(kPrimPrefix);
int checkLen = lstrlenA(primCheck);
int srcLen = lstrlenA(fragSrc);
int outLen = srcLen + prefixLen + checkLen + 16;
char *out = (char *)HeapAlloc(GetProcessHeap(), 0, outLen);
char *w = out;
int uOff = (int)(uniformInsert - fragSrc);
for (int i = 0; i < uOff; ++i)
*w++ = fragSrc[i];
const char *s = kPrimPrefix;
while (*s)
*w++ = *s++;
int bOff = (int)(brace - fragSrc);
for (int i = uOff; i < bOff; ++i)
*w++ = fragSrc[i];
s = primCheck;
while (*s)
*w++ = *s++;
const char *rest = brace;
while (*rest)
*w++ = *rest++;
*w = '\0';
return out;
}
static bool BuildProgram(const char *fragSrc)
{
char *cullSrc = nullptr;
if (g_primaryOnly)
{
cullSrc = InjectPrimaryOnly(fragSrc);
if (cullSrc)
fragSrc = cullSrc;
}
else if (g_needsCulling)
{
cullSrc = InjectCulling(fragSrc);
if (cullSrc)
fragSrc = cullSrc;
}
GLuint vs = CompileShader(GL_VERTEX_SHADER, kVertSrc);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fragSrc);
g_prog = glCreateProgram();
glAttachShader(g_prog, vs);
glAttachShader(g_prog, fs);
glLinkProgram(g_prog);
GLint ok = 0;
glGetProgramiv(g_prog, GL_LINK_STATUS, &ok);
if (!ok)
{
char log[2048];
glGetProgramInfoLog(g_prog, sizeof(log), nullptr, log);
MessageBoxA(nullptr, log, "Program link error", MB_OK | MB_ICONERROR);
return false;
}
glDeleteShader(vs);
glDeleteShader(fs);
if (cullSrc)
HeapFree(GetProcessHeap(), 0, cullSrc);
// Cache uniform locations
g_uTime = glGetUniformLocation(g_prog, "time");
g_uResolution = glGetUniformLocation(g_prog, "resolution");
g_uMouse = glGetUniformLocation(g_prog, "mouse");
g_uITime = glGetUniformLocation(g_prog, "iTime");
g_uIResolution = glGetUniformLocation(g_prog, "iResolution");
g_uIMouse = glGetUniformLocation(g_prog, "iMouse");
g_uITimeDelta = glGetUniformLocation(g_prog, "iTimeDelta");
g_uIFrame = glGetUniformLocation(g_prog, "iFrame");
g_uIDate = glGetUniformLocation(g_prog, "iDate");
// Monitor culling uniforms
g_uMonCount = glGetUniformLocation(g_prog, "_monCount");
g_uMonRects = glGetUniformLocation(g_prog, "_monRects");
g_uPrimRect = glGetUniformLocation(g_prog, "_primRect");
return true;
}
// PickRandomShader removed — embedded resources used instead
static bool InitGL(HWND hwnd, const char *fragSrcIn)
{
// 1. Create a dummy context to get wglCreateContextAttribsARB
PIXELFORMATDESCRIPTOR pfd = {};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
HDC dc = GetDC(hwnd);
int fmt = ChoosePixelFormat(dc, &pfd);
SetPixelFormat(dc, fmt, &pfd);
HGLRC tempCtx = wglCreateContext(dc);
wglMakeCurrent(dc, tempCtx);
auto wglCreateContextAttribsARB =
(PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
wglSwapIntervalEXT =
(PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
// 2. Real context (OpenGL 2.1 is enough for GLSL 1.10)
HGLRC ctx = wglCreateContextAttribsARB
? wglCreateContextAttribsARB(dc, nullptr, nullptr)
: tempCtx;
wglMakeCurrent(dc, ctx);
if (tempCtx != ctx)
wglDeleteContext(tempCtx);
g_hdc = dc;
g_hglrc = ctx;
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(1); // vsync
// 3. Load extension functions
LOAD_GL(PFNGLCREATESHADERPROC, glCreateShader);
LOAD_GL(PFNGLSHADERSOURCEPROC, glShaderSource);
LOAD_GL(PFNGLCOMPILESHADERPROC, glCompileShader);
LOAD_GL(PFNGLCREATEPROGRAMPROC, glCreateProgram);
LOAD_GL(PFNGLATTACHSHADERPROC, glAttachShader);
LOAD_GL(PFNGLLINKPROGRAMPROC, glLinkProgram);
LOAD_GL(PFNGLUSEPROGRAMPROC, glUseProgram);
LOAD_GL(PFNGLDELETESHADERPROC, glDeleteShader);
LOAD_GL(PFNGLDELETEPROGRAMPROC, glDeleteProgram);
LOAD_GL(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation);
LOAD_GL(PFNGLUNIFORM1FPROC, glUniform1f);
LOAD_GL(PFNGLUNIFORM1IPROC, glUniform1i);
LOAD_GL(PFNGLUNIFORM2FPROC, glUniform2f);
LOAD_GL(PFNGLUNIFORM3FPROC, glUniform3f);
LOAD_GL(PFNGLUNIFORM4FPROC, glUniform4f);
LOAD_GL(PFNGLUNIFORM4FVPROC, glUniform4fv);
LOAD_GL(PFNGLGETSHADERIVPROC, glGetShaderiv);
LOAD_GL(PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog);
LOAD_GL(PFNGLGETPROGRAMIVPROC, glGetProgramiv);
LOAD_GL(PFNGLGETPROGRAMINFOLOGPROC, glGetProgramInfoLog);
LOAD_GL(PFNGLACTIVETEXTUREPROC, glActiveTexture);
// 4. Compile the shader source (already in memory)
// Detect if shader has its own clock (uses iDate) — confine to primary monitor
g_shaderHasClock = (strstr(fragSrcIn, "iDate") != nullptr);
g_primaryOnly = g_shaderHasClock;
bool ok = BuildProgram(fragSrcIn);
return ok;
}
// Fade-out state — GPU crossfade between a captured shader frame and the
// uploaded desktop snapshot. The fade fragment shader is one of the embedded
// exit-*.glsl resources, picked at startup; standalone (uShader, uDesktop,
// uResolution, uFade only — no uMode dispatch).
static bool g_fadingOut = false;
static bool g_fadeOutRequested = false;
static bool g_fadeOutReady = false;
static HWND g_fadeOutReqMainWnd = nullptr;
static int g_fadeW = 0, g_fadeH = 0;
static GLuint g_shaderTex = 0;
static GLuint g_desktopTex = 0;
static GLuint g_fadeProg = 0;
static GLint g_uFadeUShader = -1;
static GLint g_uFadeUDesk = -1;
static GLint g_uFadeURes = -1;
static GLint g_uFadeUFade = -1;
static double g_fadeOutStartSec = 0.0;
static double g_fadeOutDurationSec = 0.500;
// Per-shader duration override. Looked up by the variant name (the part
// after the "exit-NN-" prefix in the resource name). Falls back to 0.500s.
static const struct { const char* name; double sec; } kExitDurations[] = {
{ "perlin", 0.800 },
{ "crossfade", 0.350 },
{ "crosswarp", 0.900 },
{ "ripple", 1.200 },
{ "poissonblur", 0.800 },
{ "boxblur", 0.800 },
};
static double LookupExitDuration(const char *name)
{
if (!name) return 0.500;
// Skip "exit-NN-" prefix to get to the variant name.
int i = 0;
while (name[i] && i < 32) {
if (name[i] == '-' && i >= 6) { ++i; break; }
++i;
}
const char *tail = name + i;
for (int k = 0; k < (int)(sizeof(kExitDurations) / sizeof(kExitDurations[0])); ++k) {
if (lstrcmpiA(tail, kExitDurations[k].name) == 0)
return kExitDurations[k].sec;
}
return 0.500;
}
// Test mode (triggered by '-' key): cycle through exit shaders without
// quitting. Each press uses the next exit shader in g_exitShaders[] order.
// Direction alternates between shader→desktop and desktop→shader.
static bool g_testActive = false;
static bool g_testRequested = false;
static int g_testNextIdx = 0;
static bool g_testToDesktop = true;
static bool g_testShowingDesk = false;
static bool g_testFrameCaptured = false;
static double g_testStartSec = 0.0;
static double g_testDurationSec = 0.500;
// Compile the given exit-shader source into g_fadeProg, replacing any
// previously linked one. Source is a borrowed pointer + size (RCDATA bytes
// are not null-terminated).
static bool BuildExitProgram(const char *src, DWORD srcLen)
{
if (!src || srcLen == 0)
return false;
// Make a null-terminated copy on the stack/heap for glShaderSource.
char *buf = (char *)HeapAlloc(GetProcessHeap(), 0, srcLen + 1);
if (!buf)
return false;
for (DWORD i = 0; i < srcLen; ++i)
buf[i] = src[i];
buf[srcLen] = '\0';
GLuint vs = CompileShader(GL_VERTEX_SHADER, kVertSrc);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, buf);
HeapFree(GetProcessHeap(), 0, buf);
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
GLint ok = 0;
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok)
{
char log[1024];
glGetProgramInfoLog(prog, sizeof(log), nullptr, log);
MessageBoxA(nullptr, log, "Exit-shader link error", MB_OK | MB_ICONERROR);
glDeleteShader(vs);
glDeleteShader(fs);
glDeleteProgram(prog);
return false;
}
glDeleteShader(vs);
glDeleteShader(fs);
// Replace previous program (if any) and re-cache uniform locations.
if (g_fadeProg)
glDeleteProgram(g_fadeProg);
g_fadeProg = prog;
g_uFadeUShader = glGetUniformLocation(g_fadeProg, "uShader");
g_uFadeUDesk = glGetUniformLocation(g_fadeProg, "uDesktop");
g_uFadeURes = glGetUniformLocation(g_fadeProg, "uResolution");
g_uFadeUFade = glGetUniformLocation(g_fadeProg, "uFade");
return true;
}
// Build the fade-out crossfade program (from the chosen exit shader) and
// allocate the two textures used during fade. Called once after InitGL
// succeeds. desktopBits is a top-down BGRA buffer of size w*h.
static bool InitFadeOutGL(int w, int h, const void *desktopBits)
{
if (g_exitCount == 0)
{
// No exit shaders embedded — fall back to instant exit (no fade).
g_fadeOutReady = false;
return false;
}
// Pick a random exit shader for this session.
SeedRng();
int pick = (int)(XorshiftNext() % (DWORD)g_exitCount);
PickEmbeddedExitShader(pick);
g_fadeOutDurationSec = LookupExitDuration(g_exitShaders[pick].name);
if (!BuildExitProgram(g_exitPickedSrc, g_exitPickedSize))
return false;
// Shader-frame texture: allocated empty, populated each fade via
// glCopyTexImage2D. Reserve full size up front.
glGenTextures(1, &g_shaderTex);
glBindTexture(GL_TEXTURE_2D, g_shaderTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Desktop-snapshot texture: uploaded once from the captured DIB. BGRA
// top-down; exit shaders flip V to compensate.
glGenTextures(1, &g_desktopTex);
glBindTexture(GL_TEXTURE_2D, g_desktopTex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, desktopBits);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glFinish();
g_fadeOutReady = true;
return true;
}
// Shader time pause state — when true, Render() uses g_pauseBeganAtMs as the
// clock so t is frozen. On unpause, g_startMs is advanced by the pause
// duration so t resumes seamlessly.
static bool g_shaderPaused = false;
static DWORD g_pauseBeganAtMs = 0;
static void Render()
{
glViewport(0, 0, g_w, g_h);
glUseProgram(g_prog);
DWORD nowMs = g_shaderPaused ? g_pauseBeganAtMs : GetTickCount();
float t = (float)(nowMs - g_startMs) / 1000.0f;
float mx = g_mx * g_w, my = g_my * g_h;
// In primary-only mode, the shader's coordinate space is the primary monitor
// (gl_FragCoord is remapped via macro and iResolution should match).
float resW = (float)g_w, resH = (float)g_h;
if (g_primaryOnly)
{
resW = g_primGL[2] - g_primGL[0];
resH = g_primGL[3] - g_primGL[1];
}
if (g_uTime != -1)
glUniform1f(g_uTime, t);
if (g_uResolution != -1)
glUniform2f(g_uResolution, resW, resH);
if (g_uMouse != -1)
glUniform2f(g_uMouse, mx, my);
if (g_uITime != -1)
glUniform1f(g_uITime, t);
if (g_uIResolution != -1)
glUniform3f(g_uIResolution, resW, resH, 1.0f);
if (g_uIMouse != -1)
glUniform4f(g_uIMouse, mx, my, 0.0f, 0.0f);
if (g_uITimeDelta != -1)
glUniform1f(g_uITimeDelta, 0.016f);
if (g_uIFrame != -1)
glUniform1i(g_uIFrame, (int)(t * 60.0f));
if (g_uIDate != -1)
{
SYSTEMTIME st;
GetLocalTime(&st);
float secsSinceMidnight = (float)st.wHour * 3600.0f + (float)st.wMinute * 60.0f + (float)st.wSecond;
glUniform4f(g_uIDate, (float)st.wYear, (float)st.wMonth, (float)st.wDay, secsSinceMidnight);
}
// Monitor culling uniforms (only set if injection is active)
if (g_uMonCount != -1)
glUniform1i(g_uMonCount, g_monCount);
if (g_uMonRects != -1)
glUniform4fv(g_uMonRects, g_monCount, g_monGL);
if (g_uPrimRect != -1)
glUniform4f(g_uPrimRect, g_primGL[0], g_primGL[1], g_primGL[2], g_primGL[3]);
// Draw fullscreen quad (4 vertices, no VBO needed with gl_VertexID trick)
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// If a fade-out was just requested, copy this frame's back buffer into
// g_shaderTex before SwapBuffers — that's the same pixels the user is
// about to see. glCopyTexImage2D stays GPU-side (no readback to CPU).
if (g_fadeOutRequested && g_shaderTex)
{
glBindTexture(GL_TEXTURE_2D, g_shaderTex);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, g_w, g_h, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
SwapBuffers(g_hdc);
}
static double NowSeconds(); // forward-declared (defined with the other timer code below)
// Render one crossfade frame. Returns the elapsed fade progress in [0,1]; the
// caller decides when to terminate. Runs entirely on the GPU using uShader and
// uDesktop textures + a uFade uniform.
static float RenderFadeOut()
{
glViewport(0, 0, g_w, g_h);
glUseProgram(g_fadeProg);
double elapsed = NowSeconds() - g_fadeOutStartSec;
float p = (float)(elapsed / g_fadeOutDurationSec);
if (p < 0.0f)
p = 0.0f;
if (p > 1.0f)
p = 1.0f;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, g_shaderTex);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, g_desktopTex);
glActiveTexture(GL_TEXTURE0);
if (g_uFadeUShader != -1)
glUniform1i(g_uFadeUShader, 0);
if (g_uFadeUDesk != -1)
glUniform1i(g_uFadeUDesk, 1);
if (g_uFadeURes != -1)
glUniform2f(g_uFadeURes, (float)g_w, (float)g_h);
if (g_uFadeUFade != -1)
glUniform1f(g_uFadeUFade, p);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
SwapBuffers(g_hdc);
return p;
}
// Render one frame of the test-mode transition. Same as RenderFadeOut but uses
// g_testStartSec/g_testDurationSec, and may swap the texture bindings so the
// transition runs desktop → shader on alternating presses.
static float RenderTestTransition()
{
glViewport(0, 0, g_w, g_h);