summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 9d8c9684646120a4c40bc6a356ef976d978b3a3e (plain)
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
#include <glad/glad.h>

#include <stdio.h>
#if WINDOWS
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif

#if ARM
#include <arm_neon.h>
#include <arm_sve.h>
#else
#include <smmintrin.h>
#endif

#include "imgui/imgui.h"
#include "imgui/backends/imgui_impl_sdl.h"
#include "imgui/backends/imgui_impl_opengl3.h"
#if WINDOWS
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <SDL_opengles2.h>
#else
#include <SDL_opengl.h>
#endif

#define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG
#include "lib/stb_image.h"

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "lib/stb_image_write.h"

// TODO(fox): Used for thumbnails. The renderer could be expanded to do this
// much more efficiently.
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "lib/stb_image_resize.h"

extern "C" {
#include "lib/miniz.h"
#include "lib/miniz.c"
}

#include "defines.h"
#include "my_math.h"
#include "structs.h"
#if STABLE
#include "stable_diffusion.h"
#endif
#include "memory.h"
#include "main.h"

#include "debug.h"
#include "functions.h"
// #include "sharebuffer.h"

SDL_Thread *Thread[8];
SDL_sem *Semaphore;

SDL_atomic_t CurrentEntry;
SDL_atomic_t QueuedEntries;
SDL_atomic_t CompletedEntries;

render_entry Entries[256];

static uint64 BitmapBlockSize;
static instruction_mode InstructionMode = instruction_mode_scalar;
static uint32 RandomGlobalIncrement = 0;

#if STABLE
#include "lib/base64.c"
#include <curl/curl.h>
#endif

#include "memory.cpp"
#include "undo.cpp"
#include "io.cpp"
#include "strings.cpp"
#include "threading.cpp"
#include "createcalls.cpp"
#if STABLE
#include "stable_diffusion.cpp"
#endif
// #include "ffmpeg_backend.cpp"
#include "my_imgui_widgets.cpp"
#include "prenderer.cpp"
#include "gl_calls.cpp"
#include "bezier.cpp"
#if 0
#include "effects.cpp"
#include "keyframes.cpp"
#include "layer.cpp"
#include "bitmap_calls.cpp"
#endif


static void
Main_RenderUI(ImGuiIO io, ImVec4 clear_color, SDL_Window *window)
{
    ImGui::Render();
    glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
    glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
    glClear(GL_COLOR_BUFFER_BIT);
    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
    SDL_GL_SwapWindow(window);
}

static void
Main_InputTest(project_data *File, project_state *State, memory *Memory, ui *UI, SDL_Window *window, GLuint textureID)
{
    ImGuiIO& io = ImGui::GetIO();
    SDL_Event event = {};
    while (SDL_PollEvent(&event))
    {
        ImGui_ImplSDL2_ProcessEvent(&event);
        if (event.type == SDL_DROPFILE) {
            char *DropFile = event.drop.file;
            Source_Generate(File, State, Memory, DropFile);
            SDL_free(DropFile);
        }
        if (event.type == SDL_QUIT)
            State->IsRunning = false;
        if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
            State->IsRunning = false;
    }

    if (UI->Warp_WantSetPos) {
        ImGui::GetIO().WantSetMousePos = true;
        io.MousePos = UI->Warp_PositionToSet;
    }

    ImGui_ImplOpenGL3_NewFrame();
    ImGui_ImplSDL2_NewFrame();

    ImGui::NewFrame();

    if (UI->Warp_WantSetPos) {
        ImGui_WarpMouseFinish(UI, io.MousePos);
        io.MouseDelta = {};
        UI->Warp_WantSetPos = false;
    }

    if (!io.WantCaptureKeyboard)
        ImGui_ProcessInputs(File, State, UI, Memory, io);

    sorted_file Sorted = File_Sort_Push(File, State, Memory);

    // These depend on sorting, so they can't be done in the ProcessInputs function:
    if (State->HotkeyInput) {
        switch (State->HotkeyInput) {
            case hotkey_none:
            {
                Assert(0);
            } break;
            case hotkey_transform:
            {
                Interact_Transform_Begin(File, Memory, State, io.MousePos, Sorted.CompArray, Sorted.LayerArray);
            } break;
            case hotkey_copy:
            {
                Clipboard_Store(File, State, Memory, Sorted.CompArray, Sorted.LayerArray, Sorted.PropertyInfo, Sorted.PropertyArray);
            } break;
            case hotkey_paste:
            {
                Clipboard_Paste(File, State, Memory, Sorted.CompArray, Sorted.LayerArray);
            } break;
        }
        State->HotkeyInput = hotkey_none;
    }


    ImGui::DockSpaceOverViewport();

    if (Debug.ToggleWindow) {
        ImGui::ShowDemoWindow();
        ImGui_DebugMemoryViewer(Memory, State);
        ImGui_DebugUndoTree(Memory, State);
    }

#if 0
    if (State->Initializing == 3) {
        Source_UICreateButton(File, State, Memory, Sorted.CompArray, Sorted.LayerArray);
        block_layer *Layera = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 2);
        // Layera->x.IsToggled = true;
        // Layera->y.IsToggled = true;
        block_layer *Layerb = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 1);
        // Layerb->x.IsToggled = true;
        // Layerb->y.IsToggled = true;
        block_layer *Layerc = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 0);
        // Layerc->x.IsToggled = true;
        // Layerc->y.IsToggled = true;
        // Layer_Select(Memory, State, 0);
        // Layer_Select(Memory, State, 1);
        // Layer_Select(Memory, State, 2);
    }
    if (State->Initializing == 2) {
        // block_composition *MainComp = (block_composition *)Memory_Block_AddressAtIndex(Memory, F_Precomps, File->PrincipalCompIndex);
        // Precomp_UICreateButton(File, State, Memory, MainComp, *Sorted.CompArray, Sorted.LayerArray);
        // Layer_DeselectAll(Memory, State, File->Layer_Count);

        block_layer *Layer = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 0);
        block_layer *Layer2 = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 1);
        block_layer *Layer3 = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, 2);
        Layer_Select(Memory, State, 0);
        // History_Entry_Commit(Memory, "Add keyframe");
        property_channel *Property = &Layer->x;
        Layer->scale.CurrentValue = 0.3;
        Layer2->scale.CurrentValue = 0.3;
        Layer3->scale.CurrentValue = 0.3;
        /*
        State->UpdateFrame = true;
        {
            bezier_point Point = { 1, {1, 0, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {10, 300, -3, 0, 3, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {20, 300, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        History_Entry_End(Memory);
        Property = &Layer->y;
        {
            bezier_point Point = { 1, {10, 50, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {0, -800, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {20, 400, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        Property = &Layer->rotation;
        {
            bezier_point Point = { 1, {0, 0, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {20, -360, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {40, 360, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        Property = &Layer->opacity;
        {
            bezier_point Point = { 1, {0, 1, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        {
            bezier_point Point = { 1, {35, 0, -5, 0, 5, 0}, interpolation_type_bezier, 0, {0, 0, 0}, 0 };
            Bezier_Add(Memory, Property, Point);
        }
        History_Entry_End(Memory);
        */
    }
#endif

    ImGui_Viewport(File, State, UI, Memory, io, textureID, Sorted.CompArray, Sorted.LayerArray);
    ImGui_Timeline(File, State, Memory, UI, io, Sorted.CompArray, Sorted.LayerArray, Sorted.PropertyInfo, Sorted.PropertyArray);
    ImGui_File(File, State, Memory, io, Sorted.CompArray, Sorted.LayerArray);
    ImGui_PropertiesPanel(File, State, UI, Memory, io);
    ImGui_ColorPanel(File, State, UI, Memory, io);
#if STABLE
    ImGui_SD_Prompt(File, State, UI, Memory, io, Sorted.CompArray, Sorted.LayerArray);
    ImGui_SD_Thumbnail(File, State, UI, Memory, io, Sorted.CompArray, Sorted.LayerArray, Sorted.SourceArray, Sorted.TempSourceCount);
#endif
    ImGui_Menu(File, State, UI, Memory, io);

    File_Sort_Pop(Memory, Sorted.Layer_SortSize, Sorted.Property_SortSize, Sorted.Source_SortSize);

#if DEBUG
    Debug.Temp = {};
#endif

    ImGui::EndFrame();
}

static void
Render_Main(void *Data, void *OutputBuffer, render_type RenderType, rectangle RenderRegion)
{
    bool32 IsRendering = true;
    Renderer_Start(Data, OutputBuffer, RenderType, RenderRegion);
    while (IsRendering) {

        // Main_InputTest(File, State, &Memory, &UI);
        Renderer_Check(&IsRendering, RenderType);
    }
}

static void *
Render_Comp(project_data *File, project_state *State, memory *Memory, ImGuiIO io,
            sorted_comp_info *SortedCompArray, sorted_layer *SortedLayerArray,
            sorted_property_info *SortedPropertyInfo, uint16 *SortedPropertyArray, uint32 CompIndex, int32 Frame_Current)
{
    block_composition *Comp = (block_composition *)Memory_Block_AddressAtIndex(Memory, F_Precomps, CompIndex);
    cache_entry *Entry_Main = Memory_Cache_Search(State, Memory, cache_entry_type_comp, CompIndex, Frame_Current);
    void *CompBuffer = Memory_Block_Bitmap_AddressAtIndex(Memory, Entry_Main->Block_StartIndex);
    uint64 Size = Comp->Width * Comp->Height * Comp->BytesPerPixel;
    Arbitrary_Zero((uint8 *)CompBuffer, Size);

    // if (Entry_Main->IsCached)
    //     return CompBuffer;

    uint64 Comp_TimeStart = GetCPUTime();

    sorted_comp_info *SortedCompInfo = &SortedCompArray[CompIndex];
    sorted_layer *SortedLayerInfo = Layer_GetSortedArray(SortedLayerArray, SortedCompArray, CompIndex);

    for (int i = 0; i < SortedCompInfo->LayerCount; i++) {
        sorted_layer SortEntry = SortedLayerInfo[i];
        uint32 Index_Physical = SortEntry.Block_Layer_Index;
        block_layer *Layer = (block_layer *)Memory_Block_AddressAtIndex(Memory, F_Layers, Index_Physical);
        if (Layer->Frame_Start <= Frame_Current &&
            Layer->Frame_End   >  Frame_Current && Layer->IsVisible)
        {
            if (State->UpdateKeyframes) {
                int32 Offset = (State->Interact_Active == interact_type_keyframe_move) ? (int32)State->Interact_Offset[0] : 0;
                for (int h = 0; h < AmountOf(Layer->Property); h++) {
                    property_channel *Property = &Layer->Property[h];
                    sorted_property_info *InfoLocation = Property_GetSortedInfo(SortedPropertyInfo, i, h);
                    uint16 *ArrayLocation = Property_GetSortedArray(SortedPropertyArray, i, h);
                    if (Property->Block_Bezier_Count) {
                        real32 MinY, MaxY;
                        Property_MinMax_Y(Memory, State, Property, InfoLocation, &MinY, &MaxY);
                        real32 Y_Increment = 1 / (MaxY - MinY);
                        v2 FirstPointPos[3];
                        bezier_point *FirstPointAddress = Bezier_LookupAddress(Memory, Property, ArrayLocation[0]);
                        Bezier_EvaluateValue(State, FirstPointAddress, FirstPointPos);
                        v2 LastPointPos[3];
                        bezier_point *LastPointAddress =  Bezier_LookupAddress(Memory, Property, ArrayLocation[Property->Keyframe_Count - 1]);
                        Bezier_EvaluateValue(State, LastPointAddress, LastPointPos);
                        if (FirstPointPos[0].x >= Frame_Current) {
                            Property->CurrentValue = FirstPointPos[0].y;
                        } else if (LastPointPos[0].x <= Frame_Current) {
                            Property->CurrentValue = LastPointPos[0].y;
                        } else {
                            int KeyframeIndex = 0;
                            for (;;) {
                                v2 PointPos[3];
                                bezier_point *PointAddress = Bezier_LookupAddress(Memory, Property, ArrayLocation[KeyframeIndex + 1]);
                                Bezier_EvaluateValue(State, PointAddress, PointPos, 1, Y_Increment);
                                if (PointPos[0].x >= Frame_Current)
                                    break;
                                KeyframeIndex++;
                            }
                            v2 PointPos[3];
                            bezier_point *PointAddress = Bezier_LookupAddress(Memory, Property, ArrayLocation[KeyframeIndex]);
                            Bezier_EvaluateValue(State, PointAddress, PointPos, 1, Y_Increment);
                            v2 NextPointPos[3];
                            bezier_point *NextPointAddress = Bezier_LookupAddress(Memory, Property, ArrayLocation[KeyframeIndex + 1]);
                            Bezier_EvaluateValue(State, NextPointAddress, NextPointPos, 1, Y_Increment);
                            if (PointAddress->Type == interpolation_type_hold) {
                                Property->CurrentValue = PointPos[0].y;
                            } else if (PointAddress->Type == interpolation_type_linear && NextPointAddress->Type == interpolation_type_linear) {
                                real32 Ratio = (Frame_Current - PointPos[0].x)  / (NextPointPos[0].x - PointPos[0].x);
                                Property->CurrentValue = PointPos[0].y + ((NextPointPos[0].y - PointPos[0].y) * Ratio);
                            } else {
                                Property->CurrentValue = Bezier_SolveYForX(PointPos[0], PointPos[0] + PointPos[2], NextPointPos[0] + NextPointPos[1], NextPointPos[0], Frame_Current);
                            }
                        }
                    }
                }
            }

            layer_bitmap_state *BitmapState = &State->Render.Bitmap[Index_Physical];
            void *BitmapAddress = NULL;
            int Width = 0, Height = 0, BytesPerPixel = 0;
            uint64 ScratchActive = 0;
            if (!Layer->IsPrecomp) {
                block_source *Source;
                if (State->PreviewSource == -1) {
                    Source = (block_source *)Memory_Block_AddressAtIndex(Memory, F_Sources, Layer->Block_Source_Index);
                } else {
                    Source = (block_source *)Memory_Block_AddressAtIndex(Memory, F_Sources, State->PreviewSource);
                }
                Width = Source->Width;
                Height = Source->Height;
                BytesPerPixel = Source->BytesPerPixel;
                if (Source->Type == source_type_principal || Source->Type == source_type_principal_temp) {
                    if (State->Interact_Active == interact_type_brush && State->Brush.LayerToPaint_Index == Index_Physical) {
                        Assert(Source->Type == source_type_principal);
                        void *SourceBitmapAddress = Memory_Block_AddressAtIndex(Memory, F_PrincipalBitmaps, Source->Bitmap_Index, 0);
                        ScratchActive = Source->Width * Source->Height * Source->BytesPerPixel;
                        void *SecondSourceBitmap = Memory_PushScratch(Memory, ScratchActive);
                        Memory_Copy((uint8 *)SecondSourceBitmap, (uint8 *)SourceBitmapAddress, ScratchActive);
                        // TODO(fox): Do all these extra precomputes really make a difference in the renderer?
                        rectangle RenderRegion = { 0, 0, Source->Width, Source->Height };
                        direct_info Info = { (real32)Source->Width, (real32)Source->Height, (real32)Source->BytesPerPixel, (real32)Source->Width * Source->BytesPerPixel,
                                             Bitmap_ByteInfo(Source->BytesPerPixel), blend_normal,
                                             RenderRegion, State->Brush.TransientBitmap};
                        Render_Main((void *)&Info, SecondSourceBitmap, render_type_notransform, State->Brush.CacheBounds);
                        BitmapAddress = SecondSourceBitmap;
                    } else {
                        BitmapAddress = Memory_Block_AddressAtIndex(Memory, F_PrincipalBitmaps, Source->Bitmap_Index, 0);
                    }
                } else {
                    cache_entry *Entry = Memory_Cache_Search(State, Memory, cache_entry_type_source, Layer->Block_Source_Index, 0);
                    if (!Entry->IsCached) {
                        uint64 Src_TimeStart = GetCPUTime();
                        block_string *Name = (block_string *)Memory_Block_AddressAtIndex(Memory, F_Strings, Source->Path_String_Index);
                        int w = 0, h = 0;
                        void *temp = stbi_load(Name->Char, &w, &h, NULL, 4);
                        Source->Width = w;
                        Source->Height = h;
                        Source->BytesPerPixel = 4;
                        uint64 Size = Source->Width * Source->Height * Source->BytesPerPixel;
                        void *Source_Address = Memory_Block_Bitmap_AddressAtIndex(Memory, Entry->Block_StartIndex);
                        Memory_Copy((uint8 *)Source_Address, (uint8 *)temp, Size);
                        stbi_image_free(temp);
                        BitmapState->ToUpdate = false;
                        BitmapState->CurrentFrame = 0;
                        Entry->CycleTime = GetCPUTime() - Src_TimeStart;
                        Layer->x.CurrentValue = Comp->Width/2;
                        Layer->y.CurrentValue = Comp->Height/2;
                        Entry->IsCached = true;
                    }
                    BitmapAddress = Memory_Block_Bitmap_AddressAtIndex(Memory, Entry->Block_StartIndex);
                }

            } else {
                block_composition *Precomp = (block_composition *)Memory_Block_AddressAtIndex(Memory, F_Precomps, Layer->Block_Source_Index);
                BitmapAddress = Render_Comp(File, State, Memory, io, SortedCompArray, SortedLayerArray,
                                            SortedPropertyInfo, SortedPropertyArray, Layer->Block_Source_Index, (int32)Layer->time.CurrentValue);
                Width = Precomp->Width;
                Height = Precomp->Height;
                BytesPerPixel = Precomp->BytesPerPixel;
            }
            Assert(BitmapAddress);

            // for (int a = 0; a < Layer->Block_Mask_Count; a++) {
            // }
            // for (int a = 0; a < Layer->Block_Effect_Count; a++) {
            // }

            /*
            for (int h = 0; h < AmountOf(Layer->Property); h++) {
                property_channel *Property = &Layer->Property[h];
                if (Property->Keyframe_Count) {
                    Property->CurrentValue = State->Frame_Current * 2;
                }
            }
            */

            transform_info T = Transform_Calculate(State, Memory, File, Layer, Comp, Width, Height, BytesPerPixel);
            T.SourceBuffer = BitmapAddress;
            rectangle RenderRegion = {0, 0, Comp->Width, Comp->Height};

            Render_Main((void *)&T, CompBuffer, render_type_main, RenderRegion);
            if (ScratchActive)
                Memory_PopScratch(Memory, ScratchActive);
        }
    }
    Entry_Main->CycleTime = GetCPUTime() - Comp_TimeStart;
    Entry_Main->IsCached = true;
    return CompBuffer;
}

static void
Main_Renderer(project_data *File, project_state *State, memory *Memory, SDL_Window *window, GLuint textureID, ImGuiIO io)
{
    block_composition *MainComp = (block_composition *)Memory_Block_AddressAtIndex(Memory, F_Precomps, File->PrincipalCompIndex);

    sorted_file Sorted = File_Sort_Push(File, State, Memory);

    void *MainCompBuffer = Render_Comp(File, State, Memory, io, Sorted.CompArray, Sorted.LayerArray,
                                      Sorted.PropertyInfo, Sorted.PropertyArray, File->PrincipalCompIndex, State->Frame_Current);

    File_Sort_Pop(Memory, Sorted.Layer_SortSize, Sorted.Property_SortSize, Sorted.Source_SortSize);

    glBindTexture(GL_TEXTURE_2D, textureID);

    int ByteFlag2 = (MainComp->BytesPerPixel == 4) ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT;
    if (State->FirstFrame) {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, MainComp->Width, MainComp->Height, 0, GL_RGBA, ByteFlag2, MainCompBuffer);
        State->FirstFrame = false;
    }
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, MainComp->Width, MainComp->Height, GL_RGBA, ByteFlag2, MainCompBuffer);

    // TODO(fox): garbage collect AV state!

    State->UpdateFrame = false;
    State->UpdateKeyframes = false;
}

int main(int argc, char *argv[]) {

    global_memory GlobalMemory = {};

    GlobalMemory.Size = ((uint64)1 * 1024 * 1024 * 1024);
    GlobalMemory.CurrentPosition = 0;

#if WINDOWS
    GlobalMemory.Address = VirtualAlloc(0, GlobalMemory.Size,
                                        MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
#else
    GlobalMemory.Address = mmap(0, GlobalMemory.Size,
                          PROT_READ | PROT_WRITE,
                          MAP_PRIVATE | MAP_ANONYMOUS,
                          -1,
                          0);
#endif

    // 1 meg per block
    BitmapBlockSize = 1024 * 1024;

    memory Memory = {};

    Memory_InitTable(&GlobalMemory, &Memory, 1 * 1024 * 1024, P_AVInfo, "Image/video headers");
    Memory_InitTable(&GlobalMemory, &Memory, 10 * 1024 * 1024, P_UndoBuffer, "Undo buffer");
    Memory_InitTable(&GlobalMemory, &Memory, 40 * 1024 * 1024, P_MiscCache, "Misc persistent");

    Memory_InitTable(&GlobalMemory, &Memory, sizeof(project_data), F_File, "File", sizeof(project_data));
    Memory_InitTable(&GlobalMemory, &Memory, 1 * 1024 * 1024, F_Precomps, "Precomps", sizeof(block_composition));
    Memory_InitTable(&GlobalMemory, &Memory, 2 * 1024 * 1024, F_Layers, "Layers", sizeof(block_layer));
    Memory_InitTable(&GlobalMemory, &Memory, 1 * 1024 * 1024, F_Sources, "Sources", sizeof(block_source));
    Memory_InitTable(&GlobalMemory, &Memory, 2 * 1024 * 1024, F_Properties, "Properties", sizeof(property_channel));
    Memory_InitTable(&GlobalMemory, &Memory, 4 * 1024 * 1024, F_Bezier, "Bezier paths (keyframes, masks)", sizeof(block_bezier));
    Memory_InitTable(&GlobalMemory, &Memory, 4 * 1024 * 1024, F_Strings, "Strings", sizeof(block_string));
    Memory_InitTable(&GlobalMemory, &Memory, (uint64)50 * 1024 * 1024, F_PrincipalBitmaps, "Principal bitmap data", BitmapBlockSize);

    Memory_InitTable(&GlobalMemory, &Memory, (uint64)5 * 1024 * 1024, B_Thumbnails, "Thumbnails");
    Memory_InitTable(&GlobalMemory, &Memory, (uint64)64 * 1024 * 1024, B_ScratchSpace, "Scratch");
    Memory_InitTable(&GlobalMemory, &Memory, (uint64)50 * 1024 * 1024, B_CachedBitmaps, "Cached bitmap buffer");


#if ARM
    InstructionMode = instruction_mode_neon;
#else
    // if (SDL_HasSSE2()) {
    //     InstructionMode = instruction_mode_sse;
    // }
    if (SDL_HasAVX2()) {
        InstructionMode = instruction_mode_avx;
    }
#endif

    project_state State_ = {};
    project_state *State = &State_;
    project_data *File = (project_data *)Memory_Block_AllocateAddress(&Memory, F_File);
    *File = {};
    File->Occupied = 1;

    // NOTE(fox): Right now I'm just gonna throw all dynamic allocs that can't
    // be simplified to the push/pop model here; will worry about how to best
    // use RAM later.

    State->Brush.PaintBuffer = (void *)((uint8 *)Memory.Slot[B_ScratchSpace].Address + Memory.ScratchPos);
    uint64 ScratchPaintSize = 2048*2048*4;
    Memory.ScratchPos += ScratchPaintSize;
    State->Brush.TransientBitmap = (void *)((uint8 *)Memory.Slot[B_ScratchSpace].Address + Memory.ScratchPos);
    ScratchPaintSize = 2048*2048*4;
    Memory.ScratchPos += ScratchPaintSize;
    State->Dump1 = (void *)((uint8 *)Memory.Slot[B_ScratchSpace].Address + Memory.ScratchPos);
    Memory.ScratchPos += ScratchPaintSize;
    State->Dump2 = (void *)((uint8 *)Memory.Slot[B_ScratchSpace].Address + Memory.ScratchPos);

    State->ClipboardBuffer = (void *)((uint8 *)Memory.Slot[B_ScratchSpace].Address + Memory.ScratchPos);
    State->ClipboardSize = 1024*1024;
    Memory.ScratchPos += State->ClipboardSize;

    ui UI = {};
    UI.Test = ImDrawListSplitter();

    block_composition *MainComp = (block_composition *)Memory_Block_AllocateAddress(&Memory, F_Precomps);

    MainComp->Width = 1280;
    MainComp->Height = 720;
    MainComp->FPS = 24;
    MainComp->BytesPerPixel = 4;
    MainComp->Frame_Count = 48;
    MainComp->Frame_End = 48;
    MainComp->Occupied = 1;
    MainComp->Name_String_Index = String_AddToFile(&Memory, "Main comp");

    File->Comp_Count = 1;

#if 0
    {
        uint16 SourceIndex = Source_Generate(File, State, &Memory, (void *)"../asset/t_a.png");
        block_source *Source = (block_source *)Memory_Block_AddressAtIndex(&Memory, F_Sources, 0);
        Source->IsSelected = true;
    }

    {
        uint16 SourceIndex = Source_Generate(File, State, &Memory, (void *)"../asset/t_b.png");
        block_source *Source = (block_source *)Memory_Block_AddressAtIndex(&Memory, F_Sources, 1);
        Source->IsSelected = true;
    }

    {
        uint16 SourceIndex = Source_Generate(File, State, &Memory, (void *)"../asset/t_c.png");
        block_source *Source = (block_source *)Memory_Block_AddressAtIndex(&Memory, F_Sources, 2);
        Source->IsSelected = true;
    }
#endif

    SDL_Init(SDL_INIT_VIDEO);

    Semaphore = SDL_CreateSemaphore(0);

    int Index[7];
    for (int i = 0; i < 7; i++) {
        Index[i] = i;
        Thread[i] = SDL_CreateThread(TestThread, "thread", (void *)&Index[i]);
    }

    // Decide GL+GLSL versions
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#if defined(IMGUI_IMPL_OPENGL_ES2)
    // GL ES 2.0 + GLSL 100
    const char* glsl_version = "#version 100";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#elif defined(__APPLE__)
    // GL 3.2 Core + GLSL 150
    const char* glsl_version = "#version 150";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#else
    // GL 3.0 + GLSL 130
    const char* glsl_version = "#version 130";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
#if DEBUG
#if ARM
    uint32 ScreenSize[2] = {(uint32)(2560/1.2), (uint32)(1600/1.2)};
#else
    real32 ScreenSize[2] = {3840/1.2, 2160/1.2};
#endif
#else
    real32 ScreenSize[2];
    SDL_DisplayMode current;
    int windowtest = SDL_GetCurrentDisplayMode(0, &current);
    if (windowtest == 0) {
        ScreenSize[0] = current.w;
        ScreenSize[1] = current.h;
    } else {
        ScreenSize[0] = 1920;
        ScreenSize[1] = 1080;
    }
#endif
    SDL_Window* window = SDL_CreateWindow("Event Tester", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ScreenSize[0], ScreenSize[1], window_flags);
    SDL_GLContext gl_context = SDL_GL_CreateContext(window);
    SDL_GL_MakeCurrent(window, gl_context);
    SDL_GL_SetSwapInterval(1); // Enable vsync

    if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
    {
        printf("Failed to initialize GLAD");
        return -1;
    }

    GL_InitDefaultShader();
    GL_InitDefaultVerts();

    SDL_GL_MakeCurrent(window, gl_context);

    SDL_Event Event;

    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableSetMousePos;
    (void)io;

    // NOTE(fox): Instead of constructing the position of the windows on
    // startup with Docking API calls (which is experimental and incomplete)
    // I'm loading the window positions from this convenient tool. ImGui by
    // default saves window position to an external .ini file, which can be
    // loaded from disk or memory.
    //  io.IniFilename = NULL;
    //  ImGui::LoadIniSettingsFromMemory(ImGuiPrefs);

    ImGui::StyleColorsDark();

    ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
    ImGui_ImplOpenGL3_Init(glsl_version);

    GLuint textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    Brush_CalcBitmapAlphaFromSize(&Memory, &State->Brush, 4);
    State_BindBrushTexture(&Memory, &State->Brush, 4);

    // File_Open(File, State, &Memory, "test");

#if STABLE
    curl_global_init(CURL_GLOBAL_ALL);
    curl_state MainHandle = {};
    curl_state ProgHandle = {};
#endif

    while (State->IsRunning)
    {
        // State->Interact_Active = interact_type_layer_move;
        // State->Interact_Offset[1] = -3.0f;

#if STABLE
        if (State->CurlActive) {
            Curl_Main(File, State, &Memory, &MainHandle, &ProgHandle);
        }
#endif

        Main_InputTest(File, State, &Memory, &UI, window, textureID);

        if (State->IsPlaying) {
            block_composition *MainComp = (block_composition *)Memory_Block_AddressAtIndex(&Memory, F_Precomps, File->PrincipalCompIndex);
            State->Frame_Current = ((State->Frame_Current + 1) >= MainComp->Frame_Count) ? 0 : State->Frame_Current + 1;
            State->UpdateFrame = true;
            State->UpdateKeyframes = true;
        }

        if (State->UpdateFrame) {
            Main_Renderer(File, State, &Memory, window, textureID, io);
        }

        Assert(Debug.ScratchState == 0);

        Main_RenderUI(io, clear_color, window);

        if (State->Initializing)
            State->Initializing--;
    }

    for (int i = 0; i < 7; i++) {
        SDL_DetachThread(Thread[i]);
    }
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplSDL2_Shutdown();
    ImGui::DestroyContext();
    SDL_Quit();

    return 0;
}