-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimgview.c
More file actions
2183 lines (1779 loc) · 59.5 KB
/
imgview.c
File metadata and controls
2183 lines (1779 loc) · 59.5 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 SDL_MAIN_USE_CALLBACKS
#include <SDL.h>
#include <SDL3/SDL_main.h>
#include <SDL3/SDL_init.h>
#include <SDL_shadercross.h>
#include <SDL_image.h>
#include "ok_lib.h"
#define PLUTOSVG_BUILD_STATIC
#define PLUTOVG_BUILD_STATIC
#include <plutosvg/plutosvg.h>
#include <windows.h>
#define bufflen 1024
char buffer [ bufflen ];
SDL_Window *window;
SDL_Rect window_rect;
SDL_GPUDevice *device;
SDL_GPUGraphicsPipeline *pipeline;
SDL_GPUSampler *sampler[2];
SDL_GPUBuffer *index_buffer;
SDL_GPUComputePipeline* blur_pipeline;
typedef struct{
int input_w, input_h;
int output_w, output_h;
} blur_uniforms;
SDL_GPUGraphicsPipeline* wireframe_pipeline;
typedef struct{
SDL_FPoint window;
SDL_FPoint A;
SDL_FPoint B;
float C;
int mode;
} wireframe_uniforms;
// Flex Quad mode:
enum{ FM_crosshair = 0, FM_rect, FM_corners, FM_diamond };
const int FM_verts[] = { 4, 8, 16, 8 };
int width;
int height;
int W, H;//total width and height of the contents onscreen
float aspect_correction;
bool CTRL, SHIFT;
int mouseX, mouseY, pmouseX, pmouseY;
float cx;
float cy;
bool mousePressed;
int clickX, clickY;
int antialiasing = 0;
bool fit = false;
bool animating = false;
bool enable_blur = false;
SDL_FRect sel_rect;
int angle_i;
float ANGLE;
SDL_FlipMode FLIP;
bool mmpan;// middle mouse pan
bool zoom_in;
bool zoom_out;
bool pan_up;
bool pan_down;
bool pan_left;
bool pan_right;
bool rotate_ccw;
bool rotate_cw;
float zoomV;
float panV;
float panVF;//vel factor for the mmpan
bool fullscreen;
//bool minimized;
int update;
const SDL_FColor bg [] = { {0 , 0 , 0 , 1.0},
{0.25, 0.25, 0.25, 1.0},
{0.5 , 0.5 , 0.5 , 1.0},
{0.75, 0.75, 0.75, 1.0},
{1.0 , 1.0 , 1.0 , 1.0} };
int sel_bg = 1;
int SDL_framerateDelay( int frame_period ){
static Uint64 then = 0;
Uint64 now = SDL_GetTicks();
int elapsed = now - then;
int delay = frame_period - elapsed;
//printf("%d - (%d - %d) = %d\n", frame_period, now, then, delay );
if( delay > 0 ){
SDL_Delay( delay );
elapsed += delay;
}
then = SDL_GetTicks();
return elapsed;
}
#define HALF_PI 1.5707963267948966192313216916397514420985846996875529104
// cycle indices "array style"
int cycle( int a, int min, int max ){
if( a < min ) return max-1;
else if( a >= max ) return min;
else return a;
}
double map(double value, double source_lo, double source_hi, double dest_lo, double dest_hi) {
return dest_lo + (dest_hi - dest_lo) * ((value - source_lo) / (source_hi - source_lo));
}
typedef struct tvert_struct{
float x, y, z;
float u, v;
} tvert;
typedef struct Matrix4x4 {
float m11, m12, m13, m14;
float m21, m22, m23, m24;
float m31, m32, m33, m34;
float m41, m42, m43, m44;
} Matrix4x4;
typedef struct uni_struct{
Matrix4x4 transform;
float w, h;
} UniDat;
void Log_M4x4( Matrix4x4 *M ){
SDL_Log( "[%g %g %g %g]", M->m11, M->m12, M->m13, M->m14 );
SDL_Log( "[%g %g %g %g]", M->m21, M->m22, M->m23, M->m24 );
SDL_Log( "[%g %g %g %g]", M->m31, M->m32, M->m33, M->m34 );
SDL_Log( "[%g %g %g %g]", M->m41, M->m42, M->m43, M->m44 );
}
typedef struct transform_struct{
float tx, ty; // translate
float scale;
float scale_i; // index, scale = 1.1 ^ scale_i
} Transform;
Transform T = (Transform){0,0,1,0};
double logarithm( double base, double x ){
return SDL_log10( x ) / SDL_log10( base );
}
SDL_Rect apply_transform_rect( SDL_Rect *rct, Transform *T ){
return (SDL_Rect){ SDL_lround( T->tx + (T->scale * rct->x) ),
SDL_lround( T->ty + (T->scale * rct->y) ),
SDL_lround( rct->w * T->scale ),
SDL_lround( rct->h * T->scale ) };
}
Matrix4x4 transformToMatrix4x4( Transform* T, float rotation, int flip) {
Matrix4x4 out = {0};
float cos_r = SDL_cosf(rotation);
float sin_r = SDL_sinf(rotation);
float flip_x = (flip & SDL_FLIP_HORIZONTAL) ? -1.0f : 1.0f;
float flip_y = (flip & SDL_FLIP_VERTICAL) ? -1.0f : 1.0f;
float icx = W * 0.5f;
float icy = H * 0.5f;
// M = S * T * c * R * F * -c
out.m11 = T->scale * cos_r * flip_x;
out.m12 = T->scale * sin_r * flip_y;
//out.m13 = 0;
out.m14 = (T->scale * cos_r * flip_x *-icx) + (T->scale * sin_r * flip_y * -icy) + (T->scale * icx) + T->tx;
out.m21 = T->scale * -sin_r * flip_x;
out.m22 = T->scale * cos_r * flip_y;
//out.m23 = 0;
out.m24 = (T->scale * -sin_r * flip_x * -icx) + (T->scale * cos_r * flip_y * -icy) + (T->scale * icy) + T->ty;
//out.m31 = 0;
//out.m32 = 0;
out.m33 = 1;
//out.m34 = 0;
//out.m41 = 0;
//out.m42 = 0;
//out.m43 = 0;
out.m44 = 1;
return out;
}
void fit_rect( SDL_FRect *A, SDL_Rect *B ){
float Ar = A->w / (float) A->h;
float Br = B->w / (float) B->h;
if( Ar > Br ){
int h = A->h * (B->w / (float) A->w);
A->x = B->x;
A->y = B->y + ((B->h - h) / 2);
A->w = B->w;
A->h = h;
}
else {
int w = A->w * (B->h / (float) A->h);
A->x = B->x + ((B->w - w) / 2);
A->y = B->y;
A->w = w;
A->h = B->h;
}
}
SDL_Rect intersect_rects(const SDL_Rect* A, const SDL_Rect* B)
{
SDL_Rect result = {0, 0, 0, 0};
int left = SDL_max(A->x, B->x);
int right = SDL_min(A->x + A->w, B->x + B->w);
int top = SDL_max(A->y, B->y);
int bottom = SDL_min(A->y + A->h, B->y + B->h);
if (left < right && top < bottom) {
result.x = left;
result.y = top;
result.w = right - left;
result.h = bottom - top;
}
return result;
}
//=================================== /Basic tooling
//=================================== Stringlist
typedef struct ok_vec_of(const char *) str_vec;
str_vec directory_list;
void destroy_str_vec( str_vec *v ){
ok_vec_foreach_rev( v, char *str ) {
SDL_free( str );
}
ok_vec_deinit( v );
}
//reverse cmp
int strrcmp( char *A, char *B ){
size_t lA = SDL_strlen(A);
size_t lB = SDL_strlen(B);
int l = SDL_min( lA, lB );
for (int i = 1; i <= l; ++i ){
int r = A[lA-i] - B[lB-i];
if( r != 0 ) return r;
}
return 0;
}
// sub-string
char* substr( char *string, int start, int stop ){
char *sub = (char*) SDL_calloc( stop-start +1, sizeof(char) );
//for (int i = start; i < stop; ++i){ sub[i-start] = string[i]; }
SDL_memcpy( sub, string + start, stop-start );
sub[ stop-start ] = '\0';
return sub;
}
//=================================== /Stringlist
//=================================== File io
char *folderpath = NULL;
int folderpath_len = 0;
int INDEX = 0;// of the present file in the list
bool remote_operation = false;
void CP_ACP_to_UTF8(char *output, const char* input) {
// from the system's code page (e.g., CP_ACP) to UTF-16 (wide characters)
int wideCharLength = MultiByteToWideChar(CP_ACP, 0, input, -1, NULL, 0);
wchar_t* wideCharStr = SDL_malloc(wideCharLength * sizeof(wchar_t));
//to wide-char (UTF-16)
MultiByteToWideChar(CP_ACP, 0, input, -1, wideCharStr, wideCharLength);
//from UTF-16 to UTF-8
int utf8Length = WideCharToMultiByte(CP_UTF8, 0, wideCharStr, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, wideCharStr, -1, output, utf8Length, NULL, NULL);
SDL_free(wideCharStr);
//return utf8Str;
}
int check_extension( char *filename ){
// 1 2 3 4 5 6 7 8 9 10
const char exts [][8] = { ".png", ".jpg", "jpeg", ".gif", ".tif", "tiff", ".ico", ".bmp", "webp", ".svg" };
size_t len = SDL_strlen( filename );
for (int i = 0; i < 10; ++i ){
if( SDL_strcasecmp( filename + len -4, exts[i] ) == 0 ){
return i+1;
}
}
return 0;
}
SDL_EnumerationResult enudir_callback(void *userdata, const char *dirname, const char *fname){
char *name = fname;
size_t dl = SDL_strlen(dirname);
if( dl > folderpath_len ){
SDL_snprintf( buffer, bufflen, "%s%s", dirname + folderpath_len, fname );
name = buffer;
}
size_t len = SDL_strlen( name );
//SDL_Log(">buf:[%s]\n", name );
if( check_extension( fname ) ){
const char **neo = ok_vec_push_new( (str_vec*)userdata );
*neo = SDL_calloc( len+1, sizeof(char) );
SDL_memcpy( *neo, name, len+1 );
}
else{
char *path = name;
if( remote_operation ){
SDL_snprintf( buffer+512, 512, "%s%s", dirname, fname );
path = buffer+512;
}
SDL_PathInfo info = {0};
SDL_GetPathInfo( path, &info );
if( info.type == SDL_PATHTYPE_DIRECTORY ){
//SDL_Log(" found dir: [%s]", name );
const char **neo = ok_vec_push_new( (str_vec*)userdata );
*neo = SDL_calloc( len+2, sizeof(char) );
SDL_snprintf( *neo, len+2, "%s\\", name );
}
}
return SDL_ENUM_CONTINUE;
}
void shuffle_str_list( const char **deck, int len ){
for (int i = 0; i < len-2; ++i){
int ni = i+1 + SDL_rand( len - (i+1) );
char *temp = deck[i];
deck[i] = deck[ni];
deck[ni] = temp;
}
}
void load_folderlist( str_vec *list, char *pfname, int depth ){
//SDL_Log("load_folderlist( %s, %d );\n", pfname, depth );
ok_vec_init( list );
if( !SDL_EnumerateDirectory( folderpath, enudir_callback, list ) ){
SDL_Log("SDL_EnumerateDirectory (1) error: %s", SDL_GetError());
SDL_Log(">{%s}", folderpath );
}
depth -= 1;
while( depth > 0 ){
//SDL_Log("looking for subfolders...");
int new_subdirs = 0;
ok_vec_foreach_rev( list, char *p ) {
size_t l = SDL_strlen(p);
if( p[l-1] == '\\' ){
//SDL_Log( "new subfolder: %s\n", p );
SDL_snprintf( buffer, bufflen, "%s%s", folderpath, p );
if( !SDL_EnumerateDirectory( buffer, enudir_callback, list ) ){
SDL_Log("SDL_EnumerateDirectory (2) error: %s", SDL_GetError());
SDL_Log(">{%s}", buffer );
}
ok_vec_remove( list, p );
SDL_free( p );
new_subdirs += 1;
}
}
if( new_subdirs <= 0 ) break;
depth -= 1;
}
// find where we are in the directory
for (int i = 0; i < ok_vec_count( list ); ++i){
if( strrcmp( pfname, ok_vec_get( list, i ) ) == 0 ){
INDEX = i;
break;
}
}
}
//=================================== /File io
//=================================== Image
void regularize_surface( SDL_Surface **S, SDL_PixelFormat target ){
if( (*S)->format != target ){
//SDL_Log("diff formats!! converting...");
SDL_Surface *neo = SDL_ConvertSurface( *S, target );
if( neo == NULL ) SDL_Log( "failed to convert: \"%s\"", SDL_GetError() );
SDL_DestroySurface( *S );
*S = neo;
}
}
SDL_GPUShader* LoadShader( SDL_GPUDevice* device, const char* shaderFilename ){
// Auto-detect the shader stage from the file name for convenience
SDL_GPUShaderStage stage;
if (SDL_strstr(shaderFilename, ".vert")){
stage = SDL_GPU_SHADERSTAGE_VERTEX;
}
else if (SDL_strstr(shaderFilename, ".frag")){
stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
}
else if (SDL_strstr(shaderFilename, ".comp")){
SDL_Log("compute.........");
return NULL;
}
else{
SDL_Log("Invalid shader stage!");
return NULL;
}
SDL_GPUShaderFormat format = SDL_GPU_SHADERFORMAT_SPIRV;
const char *entrypoint = "main";
void* code = NULL;
size_t codesize = 0;
const char* BasePath = SDL_GetBasePath();
char src_path [256];
SDL_snprintf(src_path, sizeof(src_path), "%sShaders\\Source\\%s.hlsl", BasePath, shaderFilename);
SDL_PathInfo src_info = {0};
bool src_exists = SDL_GetPathInfo( src_path, &src_info );
// Check if we have it already compiled.
char comp_path [256];
SDL_snprintf(comp_path, sizeof(comp_path), "%sShaders\\Compiled\\SPIRV\\%s.spv", BasePath, shaderFilename);
SDL_PathInfo comp_info = {0};
bool comp_exists = SDL_GetPathInfo( comp_path, &comp_info );
if( comp_exists && ( !src_exists || (src_exists && comp_info.modify_time >= src_info.modify_time) ) ){
SDL_Log( "Loading pre-compiled [%s]", shaderFilename );
code = SDL_LoadFile(comp_path, &codesize);
if( code == NULL && src_exists ) goto compile_it;
}
// If we don't, compile it
else{
compile_it:;
void* src_code = SDL_LoadFile(src_path, &codesize);
if (src_code == NULL){
SDL_Log("Failed to load shader [%s] from disk: %s", shaderFilename, SDL_GetError() );
return NULL;
}
SDL_Log( "Compiling [%s]...", shaderFilename );
SDL_ShaderCross_HLSL_Info hlsl_info = (SDL_ShaderCross_HLSL_Info){
.source = src_code, /**< The HLSL source code for the shader. */
.entrypoint = "main", /**< The entry point function name for the shader in UTF-8. */
.include_dir = NULL, /**< The include directory for shader code. Optional, can be NULL. */
.defines = NULL, /**< An array of defines. Optional, can be NULL. If not NULL, must be terminated with a fully NULL define struct. */
.shader_stage = stage, /**< The shader stage to compile the shader with. */
.props = 0 /**< A properties ID for extensions. Should be 0 if no extensions are needed. */
};
code = SDL_ShaderCross_CompileSPIRVFromHLSL( &hlsl_info, &codesize );
SDL_free( src_code );
if( code == NULL ){
SDL_Log("Failed to compile shader [%s]: %s", shaderFilename, SDL_GetError() );
return NULL;
}
SDL_IOStream *cf = SDL_IOFromFile( comp_path, "wb" );
if( SDL_WriteIO( cf, code, codesize) < codesize ){
SDL_Log("Failed to save compiled shader [%s]: %s", shaderFilename, SDL_GetError() );
}
SDL_CloseIO( cf );
}
// Use reflection to automatically determine resource counts
SDL_ShaderCross_GraphicsShaderMetadata* metadata = SDL_ShaderCross_ReflectGraphicsSPIRV(code, codesize, 0);
Uint32 samplerCount = 0;
Uint32 uniformBufferCount = 0;
Uint32 storageBufferCount = 0;
Uint32 storageTextureCount = 0;
if (metadata != NULL) {
// Use reflection data to get resource counts
SDL_ShaderCross_GraphicsShaderResourceInfo* resource_info = &metadata->resource_info;
samplerCount = resource_info->num_samplers;
uniformBufferCount = resource_info->num_uniform_buffers;
storageBufferCount = resource_info->num_storage_buffers;
storageTextureCount = resource_info->num_storage_textures;
/*SDL_Log("Shader [%s] reflection: %u samplers, %u uniform buffers, %u storage buffers, %u storage textures",
shaderFilename, samplerCount, uniformBufferCount,
storageBufferCount, storageTextureCount);
*/
} else {
SDL_Log("Warning: Failed to reflect shader [%s], using default resource counts of 0", shaderFilename);
}
SDL_GPUShaderCreateInfo shaderInfo = {
.code = code,
.code_size = codesize,
.entrypoint = entrypoint,
.format = format,
.stage = stage,
.num_samplers = samplerCount,
.num_uniform_buffers = uniformBufferCount,
.num_storage_buffers = storageBufferCount,
.num_storage_textures = storageTextureCount
};
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &shaderInfo);
SDL_free( code );
if( metadata != NULL ){
SDL_free( metadata );
}
if( shader == NULL ){
SDL_Log("Failed to create shader: %s", SDL_GetError() );
return NULL;
}
else return shader;
}
SDL_GPUComputePipeline* CreateComputePipelineFromShader( SDL_GPUDevice* device, const char* shaderFilename ){
SDL_GPUShaderFormat format = SDL_GPU_SHADERFORMAT_SPIRV;
const char *entrypoint = "main";
Uint8 *bytecode = NULL;
size_t bytecode_size = 0;
const char* BasePath = SDL_GetBasePath();
char src_path [256];
SDL_snprintf(src_path, sizeof(src_path), "%sShaders\\Source\\%s.hlsl", BasePath, shaderFilename);
SDL_PathInfo src_info = {0};
bool src_exists = SDL_GetPathInfo( src_path, &src_info );
// Check if we have it already compiled.
char comp_path [256];
SDL_snprintf(comp_path, sizeof(comp_path), "%sShaders\\Compiled\\SPIRV\\%s.spv", BasePath, shaderFilename);
SDL_PathInfo comp_info = {0};
bool comp_exists = SDL_GetPathInfo( comp_path, &comp_info );
if( comp_exists && ( !src_exists || (src_exists && comp_info.modify_time >= src_info.modify_time) ) ){
SDL_Log( "Loading pre-compiled [%s]", shaderFilename );
bytecode = SDL_LoadFile(comp_path, &bytecode_size);
if( bytecode == NULL && src_exists ) goto compile_it;
}
// If we don't, compile it
else{
compile_it:;
size_t src_codesize = 0;
Uint8* src_code = SDL_LoadFile(src_path, &src_codesize);
if (src_code == NULL){
SDL_Log("Failed to load shader [%s] from disk: %s", shaderFilename, SDL_GetError() );
return NULL;
}
SDL_Log( "Compiling [%s]...", shaderFilename );
SDL_ShaderCross_HLSL_Info hlsl_info = (SDL_ShaderCross_HLSL_Info){
.source = src_code, /**< The HLSL source code for the shader. */
.entrypoint = "main", /**< The entry point function name for the shader in UTF-8. */
.include_dir = NULL, /**< The include directory for shader code. Optional, can be NULL. */
.defines = NULL, /**< An array of defines. Optional, can be NULL. If not NULL, must be terminated with a fully NULL define struct. */
.shader_stage = SDL_SHADERCROSS_SHADERSTAGE_COMPUTE, /**< The shader stage to compile the shader with. */
.props = 0 /**< A properties ID for extensions. Should be 0 if no extensions are needed. */
};
bytecode = SDL_ShaderCross_CompileSPIRVFromHLSL( &hlsl_info, &bytecode_size );
SDL_free( src_code );
if( bytecode == NULL ){
SDL_Log("Failed to compile shader [%s]: %s", shaderFilename, SDL_GetError() );
return NULL;
}
SDL_IOStream *cf = SDL_IOFromFile( comp_path, "wb" );
if( SDL_WriteIO( cf, bytecode, bytecode_size) < bytecode_size ){
SDL_Log("Failed to save compiled shader [%s]: %s", shaderFilename, SDL_GetError() );
}
SDL_CloseIO( cf );
}
SDL_ShaderCross_ComputePipelineMetadata *metadata = SDL_ShaderCross_ReflectComputeSPIRV( bytecode,
bytecode_size,
0 );
SDL_ShaderCross_SPIRV_Info spirv_info = {
.bytecode = bytecode, /**< The SPIRV bytecode. */
.bytecode_size = bytecode_size, /**< The length of the SPIRV bytecode. */
.entrypoint = "main", /**< The entry point function name for the shader in UTF-8. */
.shader_stage = SDL_SHADERCROSS_SHADERSTAGE_COMPUTE, /**< The shader stage to transpile the shader with. */
};
SDL_GPUComputePipeline* pipeline = SDL_ShaderCross_CompileComputePipelineFromSPIRV( device,
&spirv_info,
metadata, 0 );
SDL_free( metadata );
SDL_free( bytecode );
return pipeline;
}
typedef struct image_struct{
int type;
union{
SDL_GPUTexture *TEXTURE;
struct {
SDL_GPUTexture *ORIGINAL;
SDL_GPUTexture *SnBd;// SCALED n BLURRED
float blur_zoom_threshhold;
} B;// Big image
struct {
SDL_GPUTexture **TEXTURES;
int framecount;
int FRAME;
Uint64 NFRAME;
int *delays;
} A; //ANIMATION
} U;
SDL_Rect RCT;
SDL_GPUBuffer* vertex_buffer;
} Image;
enum image_type { INVALID = 0, SIMPLE, BIG, ANIMATION };
void process_animation( Image *img, IMG_Animation *ANIM ){
img->type = ANIMATION;
img->RCT = (SDL_Rect){ 0, 0, ANIM->frames[0]->w, ANIM->frames[0]->h };
int scalemode = SDL_SCALEMODE_LINEAR;
if( img->RCT.w <= 256 || img->RCT.h <= 256 ){
antialiasing = 1;//SDL_SCALEMODE_NEAREST;//SDL_SCALEMODE_PIXELART;
}
//SDL_SetTextureScaleMode( img->U.A.TEXTURES[f], antialiasing );
SDL_GPUTransferBufferCreateInfo quadbuf_CI = {
.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
.size = (sizeof(tvert) * 4)
};
SDL_GPUTransferBuffer* quad_buffer = SDL_CreateGPUTransferBuffer( device, &quadbuf_CI );
tvert* dat = SDL_MapGPUTransferBuffer( device, quad_buffer, false );
dat[0] = (tvert) { 0, 0, 0, 0, 0 };
dat[1] = (tvert) { ANIM->frames[0]->w, 0, 0, 1, 0 };
dat[2] = (tvert) { ANIM->frames[0]->w, ANIM->frames[0]->h, 0, 1, 1 };
dat[3] = (tvert) { 0, ANIM->frames[0]->h, 0, 0, 1 };
SDL_UnmapGPUTransferBuffer(device, quad_buffer);
SDL_GPUBufferCreateInfo vertbuf_CI = {
.usage = SDL_GPU_BUFFERUSAGE_VERTEX,
.size = sizeof(tvert) * 4
};
img->vertex_buffer = SDL_CreateGPUBuffer( device, &vertbuf_CI );
//SDL_SetGPUBufferName( device, img->vertex_buffer, "texture vertex buffer" );
//SDL_Log("uploading quad to GPU...");
SDL_GPUCommandBuffer* cmdbuf = SDL_AcquireGPUCommandBuffer(device);
SDL_GPUCopyPass* copyPass = SDL_BeginGPUCopyPass(cmdbuf);
SDL_GPUTransferBufferLocation location_V = {
.transfer_buffer = quad_buffer,
.offset = 0
};
SDL_GPUBufferRegion region_V = {
.buffer = img->vertex_buffer,
.offset = 0,
.size = sizeof(tvert) * 4
};
SDL_UploadToGPUBuffer( copyPass, &location_V, ®ion_V, false );
SDL_EndGPUCopyPass( copyPass );
SDL_SubmitGPUCommandBuffer( cmdbuf );
SDL_ReleaseGPUTransferBuffer(device, quad_buffer);
img->U.A.framecount = ANIM->count;
img->U.A.TEXTURES = SDL_malloc( img->U.A.framecount * sizeof( SDL_GPUTexture* ) );
for (int f = 0; f < img->U.A.framecount; ++f ){
//img->U.A.TEXTURES[f] = SDL_CreateTextureFromSurface( R, ANIM->frames[f] );
regularize_surface( ANIM->frames + f, SDL_PIXELFORMAT_ABGR8888 );
SDL_GPUTextureCreateInfo texture_CI = {
.type = SDL_GPU_TEXTURETYPE_2D,
.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
.width = ANIM->frames[f]->w,
.height = ANIM->frames[f]->h,
.layer_count_or_depth = 1,
.num_levels = 1,
.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER
};
img->U.A.TEXTURES[f] = SDL_CreateGPUTexture(device, &texture_CI);
//SDL_SetGPUTextureName( device, img->U.A.TEXTURES[f], path );
SDL_GPUTransferBufferCreateInfo TTB_CI = {
.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
.size = ANIM->frames[f]->w * ANIM->frames[f]->h * 4
};
SDL_GPUTransferBuffer* texture_buffer = SDL_CreateGPUTransferBuffer( device, &TTB_CI );
Uint8* textureTransferPtr = SDL_MapGPUTransferBuffer( device, texture_buffer, false );
SDL_memcpy(textureTransferPtr, ANIM->frames[f]->pixels, ANIM->frames[f]->w * ANIM->frames[f]->h * 4);
SDL_UnmapGPUTransferBuffer(device, texture_buffer);
//SDL_Log("uploading texture to GPU...");
cmdbuf = SDL_AcquireGPUCommandBuffer(device);
copyPass = SDL_BeginGPUCopyPass(cmdbuf);
SDL_GPUTextureTransferInfo transfer_info_T = {
.transfer_buffer = texture_buffer,
.offset = 0, /* Zeros out the rest */
};
SDL_GPUTextureRegion region_T = {
.texture = img->U.A.TEXTURES[f],
.w = ANIM->frames[f]->w,
.h = ANIM->frames[f]->h,
.d = 1
};
SDL_UploadToGPUTexture( copyPass, &transfer_info_T, ®ion_T, false );
SDL_EndGPUCopyPass( copyPass );
SDL_SubmitGPUCommandBuffer( cmdbuf );
//SDL_DestroySurface( ANIM->frames[f] );
SDL_ReleaseGPUTransferBuffer(device, texture_buffer);
//SDL_Log("done!");
}
img->U.A.delays = SDL_malloc( img->U.A.framecount * sizeof( int ) );
SDL_memcpy( img->U.A.delays, ANIM->delays, img->U.A.framecount * sizeof( int ) );
img->U.A.FRAME = 0;
img->U.A.NFRAME = SDL_GetTicks() + ANIM->delays[0];
img->RCT = (SDL_Rect){ 0, 0, ANIM->w, ANIM->h };
}
void process_big_img( Image *img ){
SDL_Log("processing a big'un!");
img->type = BIG;
img->U.B.SnBd = NULL;
SDL_FRect target = (SDL_FRect){ 0,0,img->RCT.w, img->RCT.h };
if( img->RCT.w > 2*width || img->RCT.h > 2*height ){
SDL_Rect double_window = (SDL_Rect){ 0,0, 2*width, 2*height };
fit_rect( &target, &double_window );
}
img->U.B.blur_zoom_threshhold = 1.333 * ( height / target.h );
SDL_Log( "img->U.B.blur_zoom_threshhold = %g", img->U.B.blur_zoom_threshhold );
img->U.B.SnBd = SDL_CreateGPUTexture( device, &(SDL_GPUTextureCreateInfo ){
.type = SDL_GPU_TEXTURETYPE_2D,
.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
.width = target.w,
.height = target.h,
.layer_count_or_depth = 1,
.num_levels = 1,
.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE
});
SDL_Log( "Created a %gx%g texture, original is %dx%d", target.w, target.h, img->RCT.w, img->RCT.h );
SDL_GPUCommandBuffer* cmdbuf = SDL_AcquireGPUCommandBuffer(device);
if (cmdbuf == NULL){
SDL_Log("AcquireGPUCommandBuffer failed: %s", SDL_GetError());
return;
}
SDL_GPUComputePass *computePass = SDL_BeginGPUComputePass(
cmdbuf,
&(SDL_GPUStorageTextureReadWriteBinding){
.texture = img->U.B.SnBd,
.layer = 0,
.mip_level = 0,
.cycle = true
},
1,
NULL,
0);
SDL_BindGPUComputePipeline(computePass, blur_pipeline);
SDL_BindGPUComputeSamplers(
computePass,
0,
&(SDL_GPUTextureSamplerBinding){
.texture = img->U.B.ORIGINAL,
.sampler = sampler[1]
},
1);
blur_uniforms BUs = {
.input_w = img->RCT.w,
.input_h = img->RCT.h,
.output_w = target.w,
.output_h = target.h,
};
SDL_PushGPUComputeUniformData(cmdbuf, 0, &BUs, sizeof(blur_uniforms));
SDL_DispatchGPUCompute(computePass, (target.w +7) / 8, (target.h +7) / 8, 1);
SDL_EndGPUComputePass(computePass);
SDL_SubmitGPUCommandBuffer(cmdbuf);
SDL_Log( "Done!");
}
void animation_tick( Image *img ){
Uint64 now = SDL_GetTicks();
if( now >= img->U.A.NFRAME ){
img->U.A.FRAME = cycle( img->U.A.FRAME + 1, 0, img->U.A.framecount );
img->U.A.NFRAME = now + img->U.A.delays[ img->U.A.FRAME ];
}
}
void destroy_Image( Image *img ){
switch( img->type ){
case SIMPLE:
if( img->U.TEXTURE != NULL ){
SDL_ReleaseGPUTexture( device, img->U.TEXTURE );
img->U.TEXTURE = NULL;
}
break;
case BIG:
SDL_ReleaseGPUTexture( device, img->U.B.ORIGINAL ); img->U.B.ORIGINAL = NULL;
SDL_ReleaseGPUTexture( device, img->U.B.SnBd ); img->U.B.SnBd = NULL;
break;
case ANIMATION:
for (int f = 0; f < img->U.A.framecount; ++f ){
SDL_ReleaseGPUTexture( device, img->U.A.TEXTURES[f] );
img->U.A.TEXTURES[f] = NULL;
}
SDL_free( img->U.A.TEXTURES );
img->U.A.TEXTURES = NULL;
SDL_free( img->U.A.delays );
img->U.A.delays = NULL;
break;
}
SDL_ReleaseGPUBuffer(device, img->vertex_buffer);
img->type = INVALID;
}
/* modes:
0 - if it fits, centralize, else force-fit
1 - centralize
2 - force fit
*/
void calc_transform( Transform *T, SDL_Rect *RCT, int mode ){
if( mode == 1 || ( mode == 0 && (RCT->w < width && RCT->h < height)) ){// CENTRALIZE IT
T->tx = 0.5 * ( width - RCT->w);
T->ty = 0.5 * ( height - RCT->h);
T->scale_i = 0;
T->scale = 1;
}
else{// DOESN'T FIT... FIT IT!
SDL_FRect DST = (SDL_FRect){ RCT->x, RCT->y, RCT->w, RCT->h };
fit_rect( &DST, &window_rect );
T->tx = DST.x; T->ty = DST.y;
T->scale = DST.w / (float) RCT->w;
T->scale_i = logarithm( 1.1, T->scale );
fit = 1;
}
}
bool intersecting_or_touching( SDL_Rect *A, SDL_Rect *B ){
return ( ( A->x + A->w >= B->x ) && ( B->x + B->w >= A->x ) ) &&
( ( A->y + A->h >= B->y ) && ( B->y + B->h >= A->y ) );
}
typedef struct i2d_struct{ int i, j; } i2d;
// returns the total dimensions
i2d pack_imgs( Image *imgs, int len ){
#define rct(i) imgs[i].RCT
int *ids = SDL_malloc( len * sizeof(int) );
for(int i = 0; i < len; i++) ids[i] = i;
float targetAR = width / (float)height;
while(1){
bool done = 1;
for(int i = len-1; i > 0; i--){
if( (rct( ids[i] ).w > rct( ids[i-1] ).w && rct( ids[i] ).w > rct( ids[i-1] ).h) ||
(rct( ids[i] ).h > rct( ids[i-1] ).w && rct( ids[i] ).h > rct( ids[i-1] ).h) ){
int temp = ids[i-1];
ids[i-1] = ids[i];
ids[i] = temp;
done = 0;
}
}
if( done ) break;
}
int anchor_size = 2 * len;
i2d *anchors = SDL_malloc( anchor_size * sizeof(i2d) );
int tW = rct( ids[0] ).w;
int tH = rct( ids[0] ).h;
rct( ids[0] ).x = 0;
rct( ids[0] ).y = 0;
anchors[0] = (i2d){ tW+1, 0 };
anchors[1] = (i2d){ 0, tH+1 };
int anchor_len = 2;
for(int i = 1; i < len; i++){
int A = -1;
float best = 999999;
for(int a = 0; a < anchor_len; a++){
SDL_Rect candidate = (SDL_Rect){ anchors[a].i, anchors[a].j, rct(ids[i]).w, rct(ids[i]).h };
bool ouch = 0;
for(int j = 0; j < i; j++){
if( intersecting_or_touching( &candidate, &(imgs[ ids[j] ].RCT) ) ){
ouch = 1;
break;
}
}
if( ouch ) continue;
int right = anchors[a].i + rct(ids[i]).w;
int bottom = anchors[a].j + rct(ids[i]).h;
int nw = (right > tW)? right : tW;
int nh = (bottom > tH)? bottom : tH;
if( nw == tW && nh == tH ){
A = a;
break;
}
else{
float AR = nw / (float) nh;
float S = SDL_fabsf( targetAR - AR );
if( S < best ){
A = a;
best = S;
}
}
}
rct( ids[i] ).x = anchors[A].i;
rct( ids[i] ).y = anchors[A].j;
int right = anchors[A].i + rct(ids[i]).w;
int bottom = anchors[A].j + rct(ids[i]).h;
anchors[A] = (i2d){ rct( ids[i] ).x, bottom + 1 };
anchors[ anchor_len++ ] = (i2d){ right + 1, rct( ids[i] ).y };
if(right > tW) tW = right;