forked from jarcode-foss/glava
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.c
1654 lines (1434 loc) · 60.6 KB
/
render.c
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 <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <math.h>
#include <time.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <glad/glad.h>
#include "render.h"
#include "xwin.h"
#include "glsl_ext.h"
#define TWOPI 6.28318530718
#define PI 3.14159265359
#define swap(a, b) do { __auto_type tmp = a; a = b; b = tmp; } while (0)
#define IB_START_LEFT 0
#define IB_END_LEFT 1
#define IB_START_RIGHT 2
#define IB_END_RIGHT 3
#define IB_WORK_LEFT 4
#define IB_WORK_RIGHT 5
/* Only a single vertex shader is needed for GLava, since all rendering is done in the fragment shader
over a fullscreen quad */
#define VERTEX_SHADER_SRC \
"layout(location = 0) in vec3 pos; void main() { gl_Position = vec4(pos.x, pos.y, 0.0F, 1.0F); }"
struct gl_wcb* wcbs[2] = {};
static size_t wcbs_idx = 0;
static inline void register_wcb(struct gl_wcb* wcb) { wcbs[wcbs_idx++] = wcb; }
#define DECL_WCB(N) \
do { \
extern struct gl_wcb N; \
register_wcb(&N); \
} while (0)
/* GLSL bind source */
struct gl_bind_src {
const char* name;
int type;
int src_type;
};
/* function that can be applied to uniform binds */
struct gl_transform {
const char* name;
int type;
void (*apply)(struct gl_data*, void**, void* data);
};
/* data for sampler1D */
struct gl_sampler_data {
float* buf;
size_t sz;
};
/* GLSL uniform bind */
struct gl_bind {
const char* name;
GLuint uniform;
int type;
int src_type;
void (**transformations)(struct gl_data*, void**, void* data);
size_t t_sz;
void* udata;
};
/* GL screen framebuffer object */
struct gl_sfbo {
GLuint fbo, tex, shader;
bool valid, nativeonly;
const char* name;
struct gl_bind* binds;
size_t binds_sz;
};
/* data for screen-space overlay (quad) */
struct overlay_data {
GLuint vbuf, vao;
};
struct gl_data {
struct gl_sfbo* stages;
struct overlay_data overlay;
GLuint audio_tex_r, audio_tex_l, bg_tex, sm_prog;
size_t stages_sz, bufscale, avg_frames;
void* w;
struct gl_wcb* wcb;
int lww, lwh, lwx, lwy; /* last window dimensions */
int rate; /* framerate */
double tcounter;
int fcounter, ucounter, kcounter;
bool print_fps, avg_window, interpolate, force_geometry, copy_desktop,
smooth_pass, premultiply_alpha, check_fullscreen;
void** t_data;
float gravity_step, target_spu, fr, ur, smooth_distance, smooth_ratio,
smooth_factor, fft_scale, fft_cutoff;
struct {
float r, g, b, a;
} clear_color;
float* interpolate_buf[6];
int geometry[4];
};
/* load shader file */
static GLuint shaderload(const char* rpath,
GLenum type,
const char* shader,
const char* config,
struct request_handler* handlers,
int shader_version,
bool raw,
struct gl_data* gl) {
size_t s_len = strlen(shader);
/* Path buffer, used for output and */
char path[raw ? 2 : strlen(rpath) + s_len + 2];
if (raw) {
path[0] = '*';
path[1] = '\0';
}
struct stat st;
int fd = -1;
if (!raw) {
snprintf(path, sizeof(path) / sizeof(char), "%s/%s", shader, rpath);
fd = open(path, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "failed to load shader '%s': %s\n", path, strerror(errno));
return 0;
}
fstat(fd, &st);
}
/* open and create a copy with prepended header */
GLint max_uniforms;
glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &max_uniforms);
const GLchar* map = raw ? shader : mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
static const GLchar* header_fmt =
"#version %d\n"
"#define UNIFORM_LIMIT %d\n"
"#define PRE_SMOOTHED_AUDIO %d\n"
"#define SMOOTH_FACTOR %.6f\n"
"#define USE_ALPHA %d\n"
"#define PREMULTIPLY_ALPHA %d\n";
struct glsl_ext ext = {
.source = raw ? NULL : map,
.source_len = raw ? 0 : st.st_size,
.cd = shader,
.cfd = config,
.handlers = handlers,
.processed = (char*) (raw ? shader : NULL),
.p_len = raw ? s_len : 0
};
/* If this is raw input, skip processing */
if (!raw) ext_process(&ext, rpath);
size_t blen = strlen(header_fmt) + 64;
GLchar* buf = malloc((blen * sizeof(GLchar*)) + ext.p_len);
int written = snprintf(buf, blen, header_fmt, (int) shader_version, (int) max_uniforms,
gl->smooth_pass ? 1 : 0, (double) gl->smooth_factor,
1, gl->premultiply_alpha ? 1 : 0);
if (written < 0) {
fprintf(stderr, "snprintf() encoding error while prepending header to shader '%s'\n", path);
return 0;
}
memcpy(buf + written, ext.processed, ext.p_len);
if (!raw) munmap((void*) map, st.st_size);
GLuint s = glCreateShader(type);
GLint sl = (GLint) (ext.p_len + written);
glShaderSource(s, 1, (const GLchar* const*) &buf, &sl);
switch (glGetError()) {
case GL_INVALID_VALUE:
case GL_INVALID_OPERATION:
fprintf(stderr, "invalid operation while loading shader source\n");
return 0;
}
glCompileShader(s);
GLint ret, ilen;
glGetShaderiv(s, GL_COMPILE_STATUS, &ret);
if (ret == GL_FALSE) {
glGetShaderiv(s, GL_INFO_LOG_LENGTH, &ilen);
if (ilen) {
GLchar buf[ilen];
glGetShaderInfoLog(s, ilen, NULL, buf);
fprintf(stderr, "Shader compilation failed for '%s':\n", path);
fwrite(buf, sizeof(GLchar), ilen - 1, stderr);
return 0;
} else {
fprintf(stderr, "Shader compilation failed for '%s', but no info was available\n", path);
return 0;
}
}
if (!raw) ext_free(&ext);
free(buf);
close(fd);
return s;
}
/* link shaders */
#define shaderlink(...) shaderlink_f((GLuint[]) {__VA_ARGS__, 0})
static GLuint shaderlink_f(GLuint* arr) {
GLuint f, p;
int i = 0;
if ((p = glCreateProgram()) == 0) {
fprintf(stderr, "failed to create program\n");
abort();
}
while ((f = arr[i++]) != 0) {
glAttachShader(p, f);
switch (glGetError()) {
case GL_INVALID_VALUE:
fprintf(stderr, "tried to pass invalid value to glAttachShader\n");
return 0;
case GL_INVALID_OPERATION:
fprintf(stderr, "shader is already attached, or argument types "
"were invalid when calling glAttachShader\n");
return 0;
}
}
glLinkProgram(p);
GLint ret, ilen;
glGetProgramiv(p, GL_LINK_STATUS, &ret);
if (ret == GL_FALSE) {
glGetProgramiv(p, GL_INFO_LOG_LENGTH, &ilen);
if (ilen) {
GLchar buf[ilen];
glGetProgramInfoLog(p, ilen, NULL, buf);
fprintf(stderr, "Shader linking failed for program %d:\n", (int) p);
fwrite(buf, sizeof(GLchar), ilen - 1, stderr);
return 0;
} else {
fprintf(stderr, "Shader linking failed for program %d, but no info was available\n", (int) p);
return 0;
}
}
return p;
}
/* load shaders */
#define shaderbuild(gl, shader_path, c, r, v, ...) \
shaderbuild_f(gl, shader_path, c, r, v, (const char*[]) {__VA_ARGS__, 0})
static GLuint shaderbuild_f(struct gl_data* gl,
const char* shader_path,
const char* config,
struct request_handler* handlers,
int shader_version,
const char** arr) {
const char* str;
int i = 0, sz = 0, t;
while ((str = arr[i++]) != NULL) ++sz;
GLuint shaders[sz + 2];
shaders[sz + 1] = 0;
for (i = 0; i < sz; ++i) {
const char* path = arr[i];
size_t len = strlen(path);
for (t = len - 2; t >= 0; --t) {
if (path[t] == '.') {
if (!strcmp(path + t + 1, "frag") || !strcmp(path + t + 1, "glsl")) {
if (!(shaders[i] = shaderload(path, GL_FRAGMENT_SHADER,
shader_path, config, handlers,
shader_version, false, gl))) {
return 0;
}
} else if (!strcmp(path + t + 1, "vert")) {
/*
if (!(shaders[i] = shaderload(path, GL_VERTEX_SHADER, shader_path))) {
return 0;
}
*/
fprintf(stderr, "shaderbuild(): vertex shaders not allowed: %s\n", path);
abort();
} else {
fprintf(stderr, "shaderbuild(): invalid file extension: %s\n", path);
abort();
}
break;
}
}
}
/* load builtin vertex shader */
shaders[sz] = shaderload(NULL, GL_VERTEX_SHADER, VERTEX_SHADER_SRC, NULL, handlers, shader_version, true, gl);
fflush(stdout);
return shaderlink_f(shaders);
}
static GLuint create_1d_tex() {
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_1D, tex);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_REPEAT);
return tex;
}
static void update_1d_tex(GLuint tex, size_t w, float* data) {
glBindTexture(GL_TEXTURE_1D, tex);
glTexImage1D(GL_TEXTURE_1D, 0, GL_R16, w, 0, GL_RED, GL_FLOAT, data);
}
#define BIND_VEC2 0
#define BIND_VEC3 1
#define BIND_VEC4 2
#define BIND_IVEC2 3
#define BIND_IVEC3 4
#define BIND_IVEC4 5
#define BIND_INT 6
#define BIND_FLOAT 7
#define BIND_SAMPLER1D 8
#define BIND_SAMPLER2D 9
/* setup screen framebuffer object and its texture */
static void setup_sfbo(struct gl_sfbo* s, int w, int h) {
GLuint tex = s->valid ? s->tex : ({ glGenTextures(1, &s->tex); s->tex; });
GLuint fbo = s->valid ? s->fbo : ({ glGenFramebuffers(1, &s->fbo); s->fbo; });
s->valid = true;
/* bind texture and setup space */
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
/* setup and bind framebuffer to texture */
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
switch (glCheckFramebufferStatus(GL_FRAMEBUFFER)) {
case GL_FRAMEBUFFER_COMPLETE: break;
default:
fprintf(stderr, "error in frambuffer state\n");
abort();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
static void overlay(struct overlay_data* d) {
GLfloat buf[18];
buf[0] = -1.0f; buf[1] = -1.0f; buf[2] = 0.0f;
buf[3] = 1.0f; buf[4] = -1.0f; buf[5] = 0.0f;
buf[6] = -1.0f; buf[7] = 1.0f; buf[8] = 0.0f;
buf[9] = 1.0f; buf[10] = 1.0f; buf[11] = 0.0f;
buf[12] = 1.0f; buf[13] = -1.0f; buf[14] = 0.0f;
buf[15] = -1.0f; buf[16] = 1.0f; buf[17] = 0.0f;
glGenBuffers(1, &d->vbuf);
glBindBuffer(GL_ARRAY_BUFFER, d->vbuf);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 18, buf, GL_STATIC_DRAW);
glGenVertexArrays(1, &d->vao);
glBindVertexArray(d->vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, d->vbuf);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
static void drawoverlay(const struct overlay_data* d) {
glBindVertexArray(d->vao);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
#define TRANSFORM_NONE 0
#define TRANSFORM_FFT 1
#define TRANSFORM_WINDOW 2
#ifdef GLAD_DEBUG
struct err_msg {
GLenum code;
const char* msg;
const char* cname;
};
#define CODE(c) .code = c, .cname = #c
static const struct err_msg err_lookup[] = {
{ CODE(GL_INVALID_ENUM), .msg = "Invalid enum parameter" },
{ CODE(GL_INVALID_VALUE), .msg = "Invalid value parameter" },
{ CODE(GL_INVALID_OPERATION), .msg = "Invalid operation" },
{ CODE(GL_STACK_OVERFLOW), .msg = "Stack overflow" },
{ CODE(GL_STACK_UNDERFLOW), .msg = "Stack underflow" },
{ CODE(GL_OUT_OF_MEMORY), .msg = "Out of memory" },
{ CODE(GL_INVALID_FRAMEBUFFER_OPERATION), .msg = "Out of memory" },
#ifdef GL_CONTEXT_LOSS
{ CODE(GL_CONTEXT_LOSS), .msg = "Context loss (graphics device or driver reset?)" }
#endif
};
#undef CODE
static void glad_debugcb(const char* name, void *funcptr, int len_args, ...) {
GLenum err = glad_glGetError();
if (err != GL_NO_ERROR) {
const char* cname = "?", * msg = "Unknown error code";
size_t t;
for (t = 0; t < sizeof(err_lookup) / sizeof(struct err_msg); ++t) {
if (err_lookup[t].code == err) {
cname = err_lookup[t].cname;
msg = err_lookup[t].msg;
break;
}
}
fprintf(stderr, "glGetError(): %d (%s) in %s: '%s'\n",
(int) err, cname, name, msg);
abort();
}
}
#endif
#define SHADER_EXT_VERT "vert"
#define SHADER_EXT_FRAG "frag"
static struct gl_bind_src bind_sources[] = {
#define SRC_PREV 0
{ .name = "prev", .type = BIND_SAMPLER2D, .src_type = SRC_PREV },
#define SRC_AUDIO_L 1
{ .name = "audio_l", .type = BIND_SAMPLER1D, .src_type = SRC_AUDIO_L },
#define SRC_AUDIO_R 2
{ .name = "audio_r", .type = BIND_SAMPLER1D, .src_type = SRC_AUDIO_R },
#define SRC_AUDIO_SZ 3
{ .name = "audio_sz", .type = BIND_INT, .src_type = SRC_AUDIO_SZ },
#define SRC_SCREEN 4
{ .name = "screen", .type = BIND_IVEC2, .src_type = SRC_SCREEN },
#define SRC_TIME 5
{ .name = "iTime", .type = BIND_FLOAT, .src_type = SRC_TIME }
};
#define window(t, sz) (0.53836 - (0.46164 * cos(TWOPI * (double) t / (double)(sz - 1))))
#define ALLOC_ONCE(u, udata, ...) \
if (*udata == NULL) { \
u = malloc(sizeof(*u)); \
*u = (typeof(*u)) __VA_ARGS__; \
*udata = u; \
} else u = (typeof(u)) *udata;
/* type generic clamp/min/max, like in GLSL */
#define clamp(v, min, max) \
({ \
__auto_type _v = v; \
if (_v < min) _v = min; \
else if (_v > max) _v = max; \
_v; \
})
#define min(a0, b0) \
({ \
__auto_type _a = a0; \
__auto_type _b = b0; \
_a < _b ? _a : _b; \
})
#define max(a0, b0) \
({ \
__auto_type _a = a0; \
__auto_type _b = b0; \
_a > _b ? _a : _b; \
})
#define E 2.7182818284590452353
void transform_smooth(struct gl_data* d, void** udaa, void* data) {
struct gl_sampler_data* s = (struct gl_sampler_data*) data;
float* b = s->buf;
size_t
sz = s->sz,
asz = (size_t) ceil(s->sz / d->smooth_ratio);
for (int t = 0; t < asz; ++t) {
float
db = log(t), /* buffer index on log scale */
avg = 0; /* adj value averages (weighted) */
/* Calculate real indexes for sampling at this position, since the
distance is specified in scalar values */
int smin = (int) floor(powf(E, max(db - d->smooth_distance, 0)));
int smax = min((int) ceil(powf(E, db + d->smooth_distance)), sz - 1);
int count = 0;
for (int s = smin; s <= smax; ++s) {
if (b[s]) {
avg += b[s] /* / abs(powf(10, db + (t - s))) */;
count++;
}
}
avg /= count;
b[t] = avg;
}
}
void transform_gravity(struct gl_data* d, void** udata, void* data) {
struct gl_sampler_data* s = (struct gl_sampler_data*) data;
float* b = s->buf;
size_t sz = s->sz, t;
struct {
float* applied;
}* u;
ALLOC_ONCE(u, udata, { .applied = calloc(sz, sizeof(float)) });
float g = d->gravity_step * (1.0F / d->ur);
for (t = 0; t < sz; ++t) {
if (b[t] >= u->applied[t]) {
u->applied[t] = b[t] - g;
} else u->applied[t] -= g;
b[t] = u->applied[t];
}
}
void transform_average(struct gl_data* d, void** udata, void* data) {
struct gl_sampler_data* s = (struct gl_sampler_data*) data;
float* b = s->buf;
size_t sz = s->sz, t, f;
size_t tsz = sz * d->avg_frames;
float v;
bool use_window = d->avg_window;
struct {
float* bufs;
}* u;
ALLOC_ONCE(u, udata, { .bufs = calloc(tsz, sizeof(float)) });
memmove(u->bufs, &u->bufs[sz], (tsz - sz) * sizeof(float));
memcpy(&u->bufs[tsz - sz], b, sz * sizeof(float));
#define DO_AVG(w) \
do { \
for (t = 0; t < sz; ++t) { \
v = 0.0F; \
for (f = 0; f < d->avg_frames; ++f) { \
v += w * u->bufs[(f * sz) + t]; \
} \
b[t] = v / d->avg_frames; \
} \
} while (0)
if (use_window)
DO_AVG(window(f, d->avg_frames));
else
DO_AVG(1);
#undef DO_AVG
}
void transform_wrange(struct gl_data* d, void** _, void* data) {
struct gl_sampler_data* s = (struct gl_sampler_data*) data;
float* b = s->buf;
size_t sz = s->sz, t;
for (t = 0; t < sz; ++t) {
b[t] += 1.0F;
b[t] /= 2.0F;
}
}
void transform_window(struct gl_data* d, void** _, void* data) {
struct gl_sampler_data* s = (struct gl_sampler_data*) data;
float* b = s->buf;
size_t sz = s->sz, t;
for (t = 0; t < sz; ++t) {
b[t] *= window(t, sz);
}
}
void transform_fft(struct gl_data* d, void** _, void* in) {
struct gl_sampler_data* s = (struct gl_sampler_data*) in;
float* data = s->buf;
unsigned long nn = (unsigned long) (s->sz / 2);
unsigned long n, mmax, m, j, istep, i;
float wtemp, wr, wpr, wpi, wi, theta;
float tempr, tempi;
// reverse-binary reindexing
n = nn<<1;
j=1;
for (i=1; i<n; i+=2) {
if (j>i) {
swap(data[j-1], data[i-1]);
swap(data[j], data[i]);
}
m = nn;
while (m>=2 && j>m) {
j -= m;
m >>= 1;
}
j += m;
};
// here begins the Danielson-Lanczos section
mmax=2;
while (n>mmax) {
istep = mmax<<1;
theta = -(2*M_PI/mmax);
wtemp = sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi = sin(theta);
wr = 1.0;
wi = 0.0;
for (m=1; m < mmax; m += 2) {
for (i=m; i <= n; i += istep) {
j=i+mmax;
tempr = wr*data[j-1] - wi*data[j];
tempi = wr * data[j] + wi*data[j-1];
data[j-1] = data[i-1] - tempr;
data[j] = data[i] - tempi;
data[i-1] += tempr;
data[i] += tempi;
}
wtemp=wr;
wr += wr*wpr - wi*wpi;
wi += wi*wpr + wtemp*wpi;
}
mmax=istep;
}
/* abs and log scale */
for (n = 0; n < s->sz; ++n) {
if (data[n] < 0.0F) data[n] = -data[n];
data[n] = log(data[n] + 1) / 3;
data[n] *= max((((float) n / (float) s->sz) * d->fft_scale) + (1.0F - d->fft_cutoff), 1.0F);
}
}
static struct gl_transform transform_functions[] = {
{ .name = "window", .type = BIND_SAMPLER1D, .apply = transform_window },
{ .name = "fft", .type = BIND_SAMPLER1D, .apply = transform_fft },
{ .name = "wrange", .type = BIND_SAMPLER1D, .apply = transform_wrange },
{ .name = "avg", .type = BIND_SAMPLER1D, .apply = transform_average },
{ .name = "gravity", .type = BIND_SAMPLER1D, .apply = transform_gravity },
{ .name = "smooth", .type = BIND_SAMPLER1D, .apply = transform_smooth }
};
static struct gl_bind_src* lookup_bind_src(const char* str) {
size_t t;
for (t = 0; t < sizeof(bind_sources) / sizeof(struct gl_bind_src); ++t) {
if (!strcmp(bind_sources[t].name, str)) {
return &bind_sources[t];
}
}
return NULL;
}
struct renderer* rd_new(const char** paths, const char* entry,
const char* force_mod, const char* force_backend) {
xwin_wait_for_wm();
renderer* r = malloc(sizeof(struct renderer));
*r = (struct renderer) {
.alive = true,
.mirror_input = false,
.gl = malloc(sizeof(struct gl_data)),
.bufsize_request = 8192,
.rate_request = 22000,
.samplesize_request = 1024,
.audio_source_request = NULL
};
struct gl_data* gl = r->gl;
*gl = (struct gl_data) {
.w = NULL,
.wcb = NULL,
.stages = NULL,
.rate = 0,
.tcounter = 0.0D,
.fcounter = 0,
.ucounter = 0,
.kcounter = 0,
.fr = 1.0F,
.ur = 1.0F,
.print_fps = true,
.bufscale = 1,
.avg_frames = 6,
.avg_window = true,
.gravity_step = 4.2,
.interpolate = true,
.force_geometry = false,
.smooth_factor = 0.025,
.smooth_distance = 0.01,
.smooth_ratio = 4,
.bg_tex = 0,
.sm_prog = 0,
.copy_desktop = true,
.premultiply_alpha = true,
.check_fullscreen = true,
.smooth_pass = true,
.fft_scale = 10.2F,
.fft_cutoff = 0.3F,
.geometry = { 0, 0, 500, 400 },
.clear_color = { 0.0F, 0.0F, 0.0F, 0.0F }
};
bool forced = force_backend != NULL;
const char* backend = force_backend;
/* Window creation backend interfaces */
#ifdef GLAVA_GLFW
DECL_WCB(wcb_glfw);
if (!forced) backend = "glfw";
#endif
#ifdef GLAVA_GLX
DECL_WCB(wcb_glx);
if (!forced && getenv("DISPLAY")) {
backend = "glx";
}
#endif
if (!backend) {
fprintf(stderr, "No backend available for the active windowing system\n");
if (wcbs_idx == 0) {
fprintf(stderr, "None have been compiled into this build.\n");
} else {
fprintf(stderr, "Available backends:\n");
for (size_t t = 0; t < wcbs_idx; ++t) {
fprintf(stderr, "\t\"%s\"\n", wcbs[t]->name);
}
}
exit(EXIT_FAILURE);
}
printf("Using backend: '%s'\n", backend);
for (size_t t = 0; t < wcbs_idx; ++t) {
if (wcbs[t]->name && !strcmp(wcbs[t]->name, backend)) {
gl->wcb = wcbs[t];
break;
}
};
if (!gl->wcb) {
fprintf(stderr, "Invalid window creation backend selected: '%s'\n", backend);
abort();
}
#ifdef GLAD_DEBUG
printf("Assigning debug callback\n");
static bool assigned_debug_cb = false;
if (!assigned_debug_cb) {
glad_set_post_callback(glad_debugcb);
assigned_debug_cb = true;
}
#endif
gl->wcb->init();
int shader_version = 330,
context_version_major = 3,
context_version_minor = 3;
const char* module = force_mod;
char* xwintype = NULL, * wintitle = "GLava";
char** xwinstates = malloc(1);
size_t xwinstates_sz = 0;
bool loading_module = true, loading_smooth_pass = false;
struct gl_sfbo* current = NULL;
size_t t_count = 0;
#define WINDOW_HINT(request) \
{ .name = "set" #request, .fmt = "b", \
.handler = RHANDLER(name, args, { gl->wcb->set_##request(*(bool*) args[0]); }) }
struct request_handler handlers[] = {
{
.name = "setopacity", .fmt = "s",
.handler = RHANDLER(name, args, {
bool native_opacity = !strcmp("native", (char*) args[0]);
gl->premultiply_alpha = native_opacity;
gl->wcb->set_transparent(native_opacity);
if (!strcmp("xroot", (char*) args[0]))
gl->copy_desktop = true;
else
gl->copy_desktop = false;
if (!gl->copy_desktop && !native_opacity && strcmp("none", (char*) args[0])) {
fprintf(stderr, "Invalid opacity option: '%s'\n", (char*) args[0]);
exit(EXIT_FAILURE);
}
})
},
{
.name = "setmirror", .fmt = "b",
.handler = RHANDLER(name, args, { r->mirror_input = *(bool*) args[0]; })
},
{
.name = "setfullscreencheck", .fmt = "b",
.handler = RHANDLER(name, args, { gl->check_fullscreen = *(bool*) args[0]; })
},
{
.name = "setbg", .fmt = "s",
.handler = RHANDLER(name, args, {
float* results[] = {
&gl->clear_color.r,
&gl->clear_color.g,
&gl->clear_color.b,
&gl->clear_color.a
};
if (!ext_parse_color((char*) args[0], 2, results)) {
fprintf(stderr, "Invalid value for `setbg` request: '%s'\n", (char*) args[0]);
exit(EXIT_FAILURE);
}
})
},
{
.name = "setbgf", .fmt = "ffff",
.handler = RHANDLER(name, args, {
gl->clear_color.r = *(float*) args[0];
gl->clear_color.g = *(float*) args[1];
gl->clear_color.b = *(float*) args[2];
gl->clear_color.a = *(float*) args[3];
})
},
{
.name = "mod", .fmt = "s",
.handler = RHANDLER(name, args, {
if (loading_module && !force_mod) {
size_t len = strlen((char*) args[0]);
char* str = malloc(sizeof(char) * (strlen((char*) args[0]) + 1));
strncpy(str, (char*) args[0], len + 1);
module = str;
}
})
},
{
.name = "nativeonly", .fmt = "b",
.handler = RHANDLER(name, args, {
if (current)
current->nativeonly = *(bool*) args[0];
else {
fprintf(stderr, "`nativeonly` request needs module context\n");
exit(EXIT_FAILURE);
}
})
},
WINDOW_HINT(floating),
WINDOW_HINT(decorated),
WINDOW_HINT(focused),
WINDOW_HINT(maximized),
{
.name = "setversion", .fmt = "ii",
.handler = RHANDLER(name, args, {
context_version_major = *(int*) args[0];
context_version_minor = *(int*) args[1];
})
},
{
.name = "setgeometry", .fmt = "iiii",
.handler = RHANDLER(name, args, {
gl->geometry[0] = *(int*) args[0];
gl->geometry[1] = *(int*) args[1];
gl->geometry[2] = *(int*) args[2];
gl->geometry[3] = *(int*) args[3];
})
},
{
.name = "addxwinstate", .fmt = "s",
.handler = RHANDLER(name, args, {
++xwinstates_sz;
xwinstates = realloc(xwinstates, sizeof(*xwinstates) * xwinstates_sz);
xwinstates[xwinstates_sz - 1] = strdup((char*) args[0]);
})
},
{ .name = "setsource", .fmt = "s",
.handler = RHANDLER(name, args, {
r->audio_source_request = strdup((char*) args[0]); }) },
{ .name = "setforcegeometry", .fmt = "b",
.handler = RHANDLER(name, args, { gl->force_geometry = *(bool*) args[0]; }) },
{ .name = "setxwintype", .fmt = "s",
.handler = RHANDLER(name, args, { xwintype = strdup((char*) args[0]); }) },
{ .name = "setshaderversion", .fmt = "i",
.handler = RHANDLER(name, args, { shader_version = *(int*) args[0]; }) },
{ .name = "setswap", .fmt = "i",
.handler = RHANDLER(name, args, { gl->wcb->set_swap(*(int*) args[0]); }) },
{ .name = "setframerate", .fmt = "i",
.handler = RHANDLER(name, args, { gl->rate = *(int*) args[0]; }) },
{ .name = "setprintframes", .fmt = "b",
.handler = RHANDLER(name, args, { gl->print_fps = *(bool*) args[0]; }) },
{ .name = "settitle", .fmt = "s",
.handler = RHANDLER(name, args, { wintitle = strdup((char*) args[0]); }) },
{ .name = "setbufsize", .fmt = "i",
.handler = RHANDLER(name, args, { r->bufsize_request = *(int*) args[0]; }) },
{ .name = "setbufscale", .fmt = "i",
.handler = RHANDLER(name, args, { gl->bufscale = *(int*) args[0]; }) },
{ .name = "setsamplerate", .fmt = "i",
.handler = RHANDLER(name, args, { r->rate_request = *(int*) args[0]; }) },
{ .name = "setsamplesize", .fmt = "i",
.handler = RHANDLER(name, args, { r->samplesize_request = *(int*) args[0]; }) },
{ .name = "setavgframes", .fmt = "i",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->avg_frames = *(int*) args[0]; }) },
{ .name = "setavgwindow", .fmt = "b",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->avg_window = *(bool*) args[0]; }) },
{ .name = "setgravitystep", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->gravity_step = *(float*) args[0]; }) },
{ .name = "setsmoothpass", .fmt = "b",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->smooth_pass = *(bool*) args[0]; }) },
{ .name = "setsmoothfactor", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->smooth_factor = *(float*) args[0]; }) },
{ .name = "setsmooth", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->smooth_distance = *(float*) args[0]; }) },
{ .name = "setsmoothratio", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->smooth_ratio = *(float*) args[0]; }) },
{ .name = "setinterpolate", .fmt = "b",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->interpolate = *(bool*) args[0]; }) },
{ .name = "setfftscale", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->fft_scale = *(float*) args[0];}) },
{ .name = "setfftcutoff", .fmt = "f",
.handler = RHANDLER(name, args, {
if (!loading_smooth_pass) gl->fft_cutoff = *(float*) args[0];}) },
{
.name = "transform", .fmt = "ss",
.handler = RHANDLER(name, args, {
size_t t;
struct gl_bind* bind = NULL;
for (t = 0; t < current->binds_sz; ++t) {
if (!strcmp(current->binds[t].name, (const char*) args[0])) {
bind = ¤t->binds[t];
break;
}
}
if (!bind) {
fprintf(stderr, "Cannot add transformation to uniform '%s':"
" uniform does not exist! (%d present in this unit)\n",
(const char*) args[0], (int) current->binds_sz);
exit(EXIT_FAILURE);
}
struct gl_transform* tran = NULL;
for (t = 0; t < sizeof(transform_functions) / sizeof(struct gl_transform); ++t) {
if (!strcmp(transform_functions[t].name, (const char*) args[1])) {
tran = &transform_functions[t];
break;
}
}
if (!tran) {
fprintf(stderr, "Cannot add transformation '%s' to uniform '%s':"
" transform function does not exist!\n",
(const char*) args[1], (const char*) args[0]);
exit(EXIT_FAILURE);
}
if (tran->type != bind->type) {
fprintf(stderr, "Cannot apply '%s' to uniform '%s': mismatching types\n",
(const char*) args[1], (const char*) args[0]);
exit(EXIT_FAILURE);
}
++bind->t_sz;
bind->transformations =
realloc(bind->transformations, bind->t_sz * sizeof(void (*)(void*)));
bind->transformations[bind->t_sz - 1] = tran->apply;