From 2364076691c0220c2be4cbd538d8cf2b07769ed5 Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Tue, 16 Jun 2020 20:50:58 +0200
Subject: [PATCH] Cleaning a bit

---
 Makefile  |   2 +-
 imgui.ini |  59 ++++++++++++++-
 main.cpp  | 216 +++++++++---------------------------------------------
 3 files changed, 94 insertions(+), 183 deletions(-)

diff --git a/Makefile b/Makefile
index 6c90da1..59ad856 100644
--- a/Makefile
+++ b/Makefile
@@ -12,7 +12,7 @@
 #
 
 #CXX = g++
-#CXX = clang++
+CXX = clang++
 
 EXE = example_sdl_opengl3
 SOURCES = main.cpp
diff --git a/imgui.ini b/imgui.ini
index 250d863..5243102 100644
--- a/imgui.ini
+++ b/imgui.ini
@@ -4,12 +4,12 @@ Size=400,400
 Collapsed=0
 
 [Window][Hello, world!]
-Pos=109,82
+Pos=65,133
 Size=703,254
 Collapsed=0
 
 [Window][Dear ImGui Demo]
-Pos=1293,55
+Pos=1218,40
 Size=550,680
 Collapsed=0
 
@@ -18,3 +18,58 @@ Pos=60,60
 Size=198,71
 Collapsed=0
 
+[Window][Example: Console]
+Pos=120,381
+Size=520,600
+Collapsed=0
+
+[Window][Dear ImGui Metrics]
+Pos=771,79
+Size=338,239
+Collapsed=0
+
+[Window][Dear ImGui Style Editor]
+Pos=60,60
+Size=339,856
+Collapsed=0
+
+[Window][Example: Simple layout]
+Pos=60,60
+Size=500,440
+Collapsed=0
+
+[Window][Example: Long text display]
+Pos=60,60
+Size=520,600
+Collapsed=0
+
+[Window][Example: Auto-resizing window]
+Pos=60,60
+Size=450,267
+Collapsed=0
+
+[Window][Same title as another window##2]
+Pos=100,200
+Size=450,61
+Collapsed=0
+
+[Window][###AnimatedTitle]
+Pos=100,300
+Size=247,48
+Collapsed=0
+
+[Window][Same title as another window##1]
+Pos=689,505
+Size=484,137
+Collapsed=0
+
+[Window][Example: Custom rendering]
+Pos=1310,581
+Size=466,391
+Collapsed=0
+
+[Window][Example: Documents]
+Pos=239,49
+Size=981,743
+Collapsed=0
+
diff --git a/main.cpp b/main.cpp
index 1acd140..b76e9de 100644
--- a/main.cpp
+++ b/main.cpp
@@ -3,60 +3,9 @@
 #include "imgui_impl_opengl3.h"
 #include <stdio.h>
 #include <SDL.h>
-
-// mpv stuff
 #include <mpv/client.h>
 #include <mpv/render_gl.h>
-
-// Ugly stuff for mpv
-static Uint32 wakeup_on_mpv_render_update, wakeup_on_mpv_events;
-
-static void die(const char *msg)
-{
-    fprintf(stderr, "%s\n", msg);
-    exit(1);
-}
-
-static void *get_proc_address_mpv(void *fn_ctx, const char *name)
-{
-    return SDL_GL_GetProcAddress(name);
-}
-
-static void on_mpv_events(void *ctx)
-{
-    SDL_Event event = {.type = wakeup_on_mpv_events};
-    SDL_PushEvent(&event);
-}
-
-static void on_mpv_render_update(void *ctx)
-{
-    SDL_Event event = {.type = wakeup_on_mpv_render_update};
-    SDL_PushEvent(&event);
-}
-
-// About Desktop OpenGL function loaders:
-//  Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
-//  Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
-//  You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
-#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
-#include <GL/gl3w.h>            // Initialize with gl3wInit()
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
-#include <GL/glew.h>            // Initialize with glewInit()
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
-#include <glad/glad.h>          // Initialize with gladLoadGL()
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
-#define GLFW_INCLUDE_NONE       // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
-#include <glbinding/Binding.h>  // Initialize with glbinding::Binding::initialize()
-#include <glbinding/gl/gl.h>
-using namespace gl;
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
-#define GLFW_INCLUDE_NONE       // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
-#include <glbinding/glbinding.h>// Initialize with glbinding::initialize()
-#include <glbinding/gl/gl.h>
-using namespace gl;
-#else
-#include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
-#endif
+#include <GL/gl3w.h>
 
 // Main code
 int main(int argc, char **argv)
@@ -64,46 +13,36 @@ int main(int argc, char **argv)
     // MPV init before SDL init
     // If I remenber, we need to set an idle thing for mpv, so that it won't close even after the end of the video (which is facheux)
     if (argc != 2)
-        die("pass a single media file as argument");
+        return 1;
 
+    // Our state
+    bool show_demo_window = true;
+    bool show_another_window = false;
+    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
+    static Uint32 wakeup_on_mpv_render_update, wakeup_on_mpv_events; /* Need to be static */
+    mpv_render_context *mpv_gl;
     mpv_handle *mpv = mpv_create();
     if (!mpv)
-        die("context init failed");
+        return 1;
 
-    // Some minor options can only be set before mpv_initialize().
+    // Some minor options can only be set before mpv_initialize(). (XXX: The idle flag)
     if (mpv_initialize(mpv) < 0)
-        die("mpv init failed");
+        return 1;
 
     mpv_request_log_messages(mpv, "debug");
-
-    // Jesus Christ SDL, you suck!
-    SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "no");
-
-    // Setup SDL
-    // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems,
-    // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!)
-    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)
+    SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "no"); // Jesus Christ SDL, you suck!
+    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
     {
         printf("Error: %s\n", SDL_GetError());
         return -1;
     }
 
-    // Decide GL+GLSL versions
-#if __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
 
     // Create window with graphics context
     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
@@ -116,74 +55,36 @@ int main(int argc, char **argv)
     SDL_GL_SetSwapInterval(1); // Enable vsync
 
     // Initialize OpenGL loader
-#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
-    bool err = gl3wInit() != 0;
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
-    bool err = glewInit() != GLEW_OK;
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
-    bool err = gladLoadGL() == 0;
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
-    bool err = false;
-    glbinding::Binding::initialize();
-#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
-    bool err = false;
-    glbinding::initialize([](const char* name) { return (glbinding::ProcAddress)SDL_GL_GetProcAddress(name); });
-#else
-    bool err = false; // If you use IMGUI_IMPL_OPENGL_LOADER_CUSTOM, your loader is likely to requires some form of initialization.
-#endif
-    if (err)
+    if (gl3wInit())
     {
         fprintf(stderr, "Failed to initialize OpenGL loader!\n");
         return 1;
     }
 
-    // TODO Name correctly those things
     int __one[] = {1};
-    auto __something = (mpv_opengl_init_params){
-        .get_proc_address = get_proc_address_mpv,
+    mpv_opengl_init_params mpv_gl_init_params = {
+        .get_proc_address = [] (void *, const char *name) -> void * { return SDL_GL_GetProcAddress(name); },
     };
 
     mpv_render_param params[] = {
         {MPV_RENDER_PARAM_API_TYPE, (void *) MPV_RENDER_API_TYPE_OPENGL},
-        {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &__something},
-        // Tell libmpv that you will call mpv_render_context_update() on render
-        // context update callbacks, and that you will _not_ block on the core
-        // ever (see <libmpv/render.h> "Threading" section for what libmpv
-        // functions you can call at all when this is active).
-        // In particular, this means you must call e.g. mpv_command_async()
-        // instead of mpv_command().
-        // If you want to use synchronous calls, either make them on a separate
-        // thread, or remove the option below (this will disable features like
-        // DR and is not recommended anyway).
-        {MPV_RENDER_PARAM_ADVANCED_CONTROL, &__one},
+        {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &mpv_gl_init_params},
+        {MPV_RENDER_PARAM_ADVANCED_CONTROL, &__one}, /* Async commands only */
         {(mpv_render_param_type)0}
     };
 
-     // This makes mpv use the currently set GL context. It will use the callback
-    // (passed via params) to resolve GL builtin functions, as well as extensions.
-    mpv_render_context *mpv_gl;
-    if (mpv_render_context_create(&mpv_gl, mpv, params) < 0)
-        die("failed to initialize mpv GL context");
+    if (mpv_render_context_create(&mpv_gl, mpv, params) < 0) /* Resolv already created context */
+        return 1;
 
-    // We use events for thread-safe notification of the SDL main loop.
-    // Generally, the wakeup callbacks (set further below) should do as least
-    // work as possible, and merely wake up another thread to do actual work.
-    // On SDL, waking up the mainloop is the ideal course of action. SDL's
-    // SDL_PushEvent() is thread-safe, so we use that.
     wakeup_on_mpv_render_update = SDL_RegisterEvents(1);
-    wakeup_on_mpv_events = SDL_RegisterEvents(1);
-    if (wakeup_on_mpv_render_update == (Uint32)-1 ||
-        wakeup_on_mpv_events == (Uint32)-1)
-        die("could not register events");
+    wakeup_on_mpv_events        = SDL_RegisterEvents(1);
+    if (wakeup_on_mpv_render_update == (Uint32)-1 || wakeup_on_mpv_events == (Uint32)-1)
+        return 1;
 
     // When normal mpv events are available.
-    mpv_set_wakeup_callback(mpv, on_mpv_events, NULL);
-
-    // When there is a need to call mpv_render_context_update(), which can
-    // request a new frame to be rendered.
-    // (Separate from the normal event handling mechanism for the sake of
-    //  users which run OpenGL on a different thread.)
-    mpv_render_context_set_update_callback(mpv_gl, on_mpv_render_update, NULL);
+    mpv_set_wakeup_callback(mpv, [](void *) -> void {SDL_Event event = {.type = wakeup_on_mpv_events}; SDL_PushEvent(&event);}, NULL);
+    // When there is a need to call mpv_render_context_update(), which can request a new frame to be rendered.
+    mpv_render_context_set_update_callback(mpv_gl, [](void *) -> void { SDL_Event event = {.type = wakeup_on_mpv_render_update}; SDL_PushEvent(&event); }, NULL);
 
     // Play this file.
     const char *cmd[] = {"loadfile", argv[1], NULL};
@@ -195,34 +96,13 @@ int main(int argc, char **argv)
     ImGuiIO& io = ImGui::GetIO(); (void)io;
     //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
     //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
-
     // Setup Dear ImGui style
     ImGui::StyleColorsDark();
-    //ImGui::StyleColorsClassic();
-
-    // Setup Platform/Renderer bindings
     ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
     ImGui_ImplOpenGL3_Init(glsl_version);
 
-    // Load Fonts
-    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
-    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
-    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
-    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
-    // - Read 'docs/FONTS.md' for more instructions and details.
-    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
-    //io.Fonts->AddFontDefault();
+    assert(io.Fonts->AddFontDefault());
     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
-    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
-    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
-    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
-    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
-    //IM_ASSERT(font != NULL);
-
-    // Our state
-    bool show_demo_window = true;
-    bool show_another_window = false;
-    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
 
     // Main loop
     bool done = false;
@@ -234,7 +114,6 @@ int main(int argc, char **argv)
         // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
         // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
         SDL_Event event;
-        int redraw = 0;
         while (SDL_PollEvent(&event))
         {
             ImGui_ImplSDL2_ProcessEvent(&event);
@@ -242,8 +121,6 @@ int main(int argc, char **argv)
                 done = true;
             if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
                 done = true;
-            if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_EXPOSED)
-                redraw = 1;
             if (event.type == SDL_KEYDOWN)
             {
                 if (event.key.keysym.sym == SDLK_SPACE)
@@ -265,57 +142,45 @@ int main(int argc, char **argv)
             }
             if (event.type == wakeup_on_mpv_render_update)
             {
-                uint64_t flags = mpv_render_context_update(mpv_gl);
-                if (flags & MPV_RENDER_UPDATE_FRAME)
-                    redraw = 1;
+                // Need to be called to update
+                mpv_render_context_update(mpv_gl);
             }
             // Happens when at least 1 new event is in the mpv event queue.
             if (event.type == wakeup_on_mpv_events)
             {
                 // Handle all remaining mpv events.
-                while (1) {
+                int count = 10;
+                while (count) {
                     mpv_event *mp_event = (mpv_event*) mpv_wait_event(mpv, 0);
                     if (mp_event->event_id == MPV_EVENT_NONE)
                         break;
                     if (mp_event->event_id == MPV_EVENT_LOG_MESSAGE) {
                         mpv_event_log_message *msg = (mpv_event_log_message *) mp_event->data;
-                        // Print log messages about DR allocations, just to
-                        // test whether it works. If there is more than 1 of
-                        // these, it works. (The log message can actually change
-                        // any time, so it's possible this logging stops working
-                        // in the future.)
                         if (strstr(msg->text, "DR image"))
                             printf("log: %s", msg->text);
                         continue;
                     }
+                    count --;
                     printf("event: %s\n", mpv_event_name(mp_event->event_id));
                 }
             }
         }
 
-        redraw = 1;
-        if (redraw)
+        /* Always redraw */
         {
             int w, h;
             int __one__one = 1;
             SDL_GetWindowSize(window, &w, &h);
-            auto __thing1 = (mpv_opengl_fbo){
+            mpv_opengl_fbo fbo = {
                 .fbo = 0,
                 .w = w,
                 .h = h,
             };
             mpv_render_param params[] = {
-                // Specify the default framebuffer (0) as target. This will
-                // render onto the entire screen. If you want to show the video
-                // in a smaller rectangle or apply fancy transformations, you'll
-                // need to render into a separate FBO and draw it manually.
-                {MPV_RENDER_PARAM_OPENGL_FBO, &__thing1},
-                // Flip rendering (needed due to flipped GL coordinate system).
+                {MPV_RENDER_PARAM_OPENGL_FBO, &fbo},
                 {MPV_RENDER_PARAM_FLIP_Y, &__one__one},
                 {(mpv_render_param_type)0}
             };
-            // See render_gl.h on what OpenGL environment mpv expects, and
-            // other API details.
             mpv_render_context_render(mpv_gl, params);
         }
 
@@ -363,25 +228,16 @@ int main(int argc, char **argv)
 
         // Rendering
         ImGui::Render();
-        // glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
-        // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
-        // glClear(GL_COLOR_BUFFER_BIT);
         ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
-
         SDL_GL_SwapWindow(window);
     }
 
-    // Destroy the GL renderer and all of the GL objects it allocated. If video
-    // is still running, the video track will be deselected.
+    /* CLEAN */
     mpv_render_context_free(mpv_gl);
-
     mpv_detach_destroy(mpv);
-
-    // Cleanup
     ImGui_ImplOpenGL3_Shutdown();
     ImGui_ImplSDL2_Shutdown();
     ImGui::DestroyContext();
-
     SDL_GL_DeleteContext(gl_context);
     SDL_DestroyWindow(window);
     SDL_Quit();
-- 
GitLab