/* ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010, 2011,2012 Giovanni Di Sirio. This file is part of ChibiOS/RT. ChibiOS/RT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ChibiOS/RT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ /** * @file templates/chconf.h * @brief Configuration file template. * @details A copy of this file must be placed in each project directory, it * contains the application specific kernel settings. * * @addtogroup config * @details Kernel related settings and hooks. * @{ */ #ifndef _CHCONF_H_ #define _CHCONF_H_ #define PORT_IDLE_THREAD_STACK_SIZE 32 #define CORTEX_USE_FPU FALSE /*===========================================================================*/ /** * @name Kernel parameters and options * @{ */ /*===========================================================================*/ /** * @brief System tick frequency. * @details Frequency of the system timer that drives the system ticks. This * setting also defines the system tick time unit. */ #if !defined(CH_FREQUENCY) || defined(__DOXYGEN__) #define CH_FREQUENCY 1000 #endif /** * @brief Round robin interval. * @details This constant is the number of system ticks allowed for the * threads before preemption occurs. Setting this value to zero * disables the preemption for threads with equal priority and the * round robin becomes cooperative. Note that higher priority * threads can still preempt, the kernel is always preemptive. * * @note Disabling the round robin preemption makes the kernel more compact * and generally faster. */ #if !defined(CH_TIME_QUANTUM) || defined(__DOXYGEN__) #define CH_TIME_QUANTUM 20 #endif /** * @brief Managed RAM size. * @details Size of the RAM area to be managed by the OS. If set to zero * then the whole available RAM is used. The core memory is made * available to the heap allocator and/or can be used directly through * the simplified core memory allocator. * * @note In order to let the OS manage the whole RAM the linker script must * provide the @p __heap_base__ and @p __heap_end__ symbols. * @note Requires @p CH_USE_MEMCORE. */ #if !defined(CH_MEMCORE_SIZE) || defined(__DOXYGEN__) #define CH_MEMCORE_SIZE 0 #endif /** * @brief Idle thread automatic spawn suppression. * @details When this option is activated the function @p chSysInit() * does not spawn the idle thread automatically. The application has * then the responsibility to do one of the following: * - Spawn a custom idle thread at priority @p IDLEPRIO. * - Change the main() thread priority to @p IDLEPRIO then enter * an endless loop. In this scenario the @p main() thread acts as * the idle thread. * . * @note Unless an idle thread is spawned the @p main() thread must not * enter a sleep state. */ #if !defined(CH_NO_IDLE_THREAD) || defined(__DOXYGEN__) #define CH_NO_IDLE_THREAD FALSE #endif /** @} */ /*===========================================================================*/ /** * @name Performance options * @{ */ /*===========================================================================*/ /** * @brief OS optimization. * @details If enabled then time efficient rather than space efficient code * is used when two possible implementations exist. * * @note This is not related to the compiler optimization options. * @note The default is @p TRUE. */ #if !defined(CH_OPTIMIZE_SPEED) || defined(__DOXYGEN__) #define CH_OPTIMIZE_SPEED TRUE #endif /** @} */ /*===========================================================================*/ /** * @name Subsystem options * @{ */ /*===========================================================================*/ /** * @brief Threads registry APIs. * @details If enabled then the registry APIs are included in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_REGISTRY) || defined(__DOXYGEN__) #define CH_USE_REGISTRY TRUE #endif /** * @brief Threads synchronization APIs. * @details If enabled then the @p chThdWait() function is included in * the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_WAITEXIT) || defined(__DOXYGEN__) #define CH_USE_WAITEXIT TRUE #endif /** * @brief Semaphores APIs. * @details If enabled then the Semaphores APIs are included in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_SEMAPHORES) || defined(__DOXYGEN__) #define CH_USE_SEMAPHORES TRUE #endif /** * @brief Semaphores queuing mode. * @details If enabled then the threads are enqueued on semaphores by * priority rather than in FIFO order. * * @note The default is @p FALSE. Enable this if you have special requirements. * @note Requires @p CH_USE_SEMAPHORES. */ #if !defined(CH_USE_SEMAPHORES_PRIORITY) || defined(__DOXYGEN__) #define CH_USE_SEMAPHORES_PRIORITY FALSE #endif /** * @brief Atomic semaphore API. * @details If enabled then the semaphores the @p chSemSignalWait() API * is included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_SEMAPHORES. */ #if !defined(CH_USE_SEMSW) || defined(__DOXYGEN__) #define CH_USE_SEMSW TRUE #endif /** * @brief Mutexes APIs. * @details If enabled then the mutexes APIs are included in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_MUTEXES) || defined(__DOXYGEN__) #define CH_USE_MUTEXES TRUE #endif /** * @brief Conditional Variables APIs. * @details If enabled then the conditional variables APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_MUTEXES. */ #if !defined(CH_USE_CONDVARS) || defined(__DOXYGEN__) #define CH_USE_CONDVARS TRUE #endif /** * @brief Conditional Variables APIs with timeout. * @details If enabled then the conditional variables APIs with timeout * specification are included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_CONDVARS. */ #if !defined(CH_USE_CONDVARS_TIMEOUT) || defined(__DOXYGEN__) #define CH_USE_CONDVARS_TIMEOUT TRUE #endif /** * @brief Events Flags APIs. * @details If enabled then the event flags APIs are included in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_EVENTS) || defined(__DOXYGEN__) #define CH_USE_EVENTS TRUE #endif /** * @brief Events Flags APIs with timeout. * @details If enabled then the events APIs with timeout specification * are included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_EVENTS. */ #if !defined(CH_USE_EVENTS_TIMEOUT) || defined(__DOXYGEN__) #define CH_USE_EVENTS_TIMEOUT TRUE #endif /** * @brief Synchronous Messages APIs. * @details If enabled then the synchronous messages APIs are included * in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_MESSAGES) || defined(__DOXYGEN__) #define CH_USE_MESSAGES TRUE #endif /** * @brief Synchronous Messages queuing mode. * @details If enabled then messages are served by priority rather than in * FIFO order. * * @note The default is @p FALSE. Enable this if you have special requirements. * @note Requires @p CH_USE_MESSAGES. */ #if !defined(CH_USE_MESSAGES_PRIORITY) || defined(__DOXYGEN__) #define CH_USE_MESSAGES_PRIORITY FALSE #endif /** * @brief Mailboxes APIs. * @details If enabled then the asynchronous messages (mailboxes) APIs are * included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_SEMAPHORES. */ #if !defined(CH_USE_MAILBOXES) || defined(__DOXYGEN__) #define CH_USE_MAILBOXES TRUE #endif /** * @brief I/O Queues APIs. * @details If enabled then the I/O queues APIs are included in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_QUEUES) || defined(__DOXYGEN__) #define CH_USE_QUEUES TRUE #endif /** * @brief Core Memory Manager APIs. * @details If enabled then the core memory manager APIs are included * in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_MEMCORE) || defined(__DOXYGEN__) #define CH_USE_MEMCORE TRUE #endif /** * @brief Heap Allocator APIs. * @details If enabled then the memory heap allocator APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_MEMCORE and either @p CH_USE_MUTEXES or * @p CH_USE_SEMAPHORES. * @note Mutexes are recommended. */ #if !defined(CH_USE_HEAP) || defined(__DOXYGEN__) #define CH_USE_HEAP TRUE #endif /** * @brief C-runtime allocator. * @details If enabled the the heap allocator APIs just wrap the C-runtime * @p malloc() and @p free() functions. * * @note The default is @p FALSE. * @note Requires @p CH_USE_HEAP. * @note The C-runtime may or may not require @p CH_USE_MEMCORE, see the * appropriate documentation. */ #if !defined(CH_USE_MALLOC_HEAP) || defined(__DOXYGEN__) #define CH_USE_MALLOC_HEAP FALSE #endif /** * @brief Memory Pools Allocator APIs. * @details If enabled then the memory pools allocator APIs are included * in the kernel. * * @note The default is @p TRUE. */ #if !defined(CH_USE_MEMPOOLS) || defined(__DOXYGEN__) #define CH_USE_MEMPOOLS TRUE #endif /** * @brief Dynamic Threads APIs. * @details If enabled then the dynamic threads creation APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_USE_WAITEXIT. * @note Requires @p CH_USE_HEAP and/or @p CH_USE_MEMPOOLS. */ #if !defined(CH_USE_DYNAMIC) || defined(__DOXYGEN__) #define CH_USE_DYNAMIC TRUE #endif /** @} */ /*===========================================================================*/ /** * @name Debug options * @{ */ /*===========================================================================*/ /** * @brief Debug option, system state check. * @details If enabled the correct call protocol for system APIs is checked * at runtime. * * @note The default is @p FALSE. */ #if !defined(CH_DBG_SYSTEM_STATE_CHECK) || defined(__DOXYGEN__) #define CH_DBG_SYSTEM_STATE_CHECK TRUE #endif /** * @brief Debug option, parameters checks. * @details If enabled then the checks on the API functions input * parameters are activated. * * @note The default is @p FALSE. */ #if !defined(CH_DBG_ENABLE_CHECKS) || defined(__DOXYGEN__) #define CH_DBG_ENABLE_CHECKS TRUE #endif /** * @brief Debug option, consistency checks. * @details If enabled then all the assertions in the kernel code are * activated. This includes consistency checks inside the kernel, * runtime anomalies and port-defined checks. * * @note The default is @p FALSE. */ #if !defined(CH_DBG_ENABLE_ASSERTS) || defined(__DOXYGEN__) #define CH_DBG_ENABLE_ASSERTS TRUE #endif /** * @brief Debug option, trace buffer. * @details If enabled then the context switch circular trace buffer is * activated. * * @note The default is @p FALSE. */ #if !defined(CH_DBG_ENABLE_TRACE) || defined(__DOXYGEN__) #define CH_DBG_ENABLE_TRACE TRUE #endif /** * @brief Debug option, stack checks. * @details If enabled then a runtime stack check is performed. * * @note The default is @p FALSE. * @note The stack check is performed in a architecture/port dependent way. * It may not be implemented or some ports. * @note The default failure mode is to halt the system with the global * @p panic_msg variable set to @p NULL. */ #if !defined(CH_DBG_ENABLE_STACK_CHECK) || defined(__DOXYGEN__) #define CH_DBG_ENABLE_STACK_CHECK TRUE #endif /** * @brief Debug option, stacks initialization. * @details If enabled then the threads working area is filled with a byte * value when a thread is created. This can be useful for the * runtime measurement of the used stack. * * @note The default is @p FALSE. */ #if !defined(CH_DBG_FILL_THREADS) || defined(__DOXYGEN__) #define CH_DBG_FILL_THREADS TRUE #endif /** * @brief Debug option, threads profiling. * @details If enabled then a field is added to the @p Thread structure that * counts the system ticks occurred while executing the thread. * * @note The default is @p TRUE. * @note This debug option is defaulted to TRUE because it is required by * some test cases into the test suite. */ #if !defined(CH_DBG_THREADS_PROFILING) || defined(__DOXYGEN__) #define CH_DBG_THREADS_PROFILING TRUE #endif /** @} */ /*===========================================================================*/ /** * @name Kernel hooks * @{ */ /*===========================================================================*/ /** * @brief Threads descriptor structure extension. * @details User fields added to the end of the @p Thread structure. */ #if !defined(THREAD_EXT_FIELDS) || defined(__DOXYGEN__) #define THREAD_EXT_FIELDS \ /* Add threads custom fields here.*/ #endif /** * @brief Threads initialization hook. * @details User initialization code added to the @p chThdInit() API. * * @note It is invoked from within @p chThdInit() and implicitily from all * the threads creation APIs. */ #if !defined(THREAD_EXT_INIT_HOOK) || defined(__DOXYGEN__) #define THREAD_EXT_INIT_HOOK(tp) { \ /* Add threads initialization code here.*/ \ } #endif /** * @brief Threads finalization hook. * @details User finalization code added to the @p chThdExit() API. * * @note It is inserted into lock zone. * @note It is also invoked when the threads simply return in order to * terminate. */ #if !defined(THREAD_EXT_EXIT_HOOK) || defined(__DOXYGEN__) #define THREAD_EXT_EXIT_HOOK(tp) { \ /* Add threads finalization code here.*/ \ } #endif /** * @brief Context switch hook. * @details This hook is invoked just before switching between threads. */ #if !defined(THREAD_CONTEXT_SWITCH_HOOK) || defined(__DOXYGEN__) #define THREAD_CONTEXT_SWITCH_HOOK(ntp, otp) { \ /* System halt code here.*/ \ } #endif /** * @brief Idle Loop hook. * @details This hook is continuously invoked by the idle thread loop. */ #if !defined(IDLE_LOOP_HOOK) || defined(__DOXYGEN__) #define IDLE_LOOP_HOOK() { \ /* Idle loop
// dear imgui: Renderer + Platform Binding for Allegro 5
// (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)

// Implemented features:
//  [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
//  [X] Platform: Clipboard support (from Allegro 5.1.12)
//  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// Issues:
//  [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
//  [ ] Platform: Missing gamepad support.

// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui, Original Allegro 5 code by @birthggd

// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
//  2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12).
//  2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
//  2018-06-13: Renderer: Backup/restore transform and clipping rectangle.
//  2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
//  2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp.
//  2018-04-18: Misc: Added support for 32-bits vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h.
//  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplAllegro5_RenderDrawData() in the .h file so you can call it yourself.
//  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
//  2018-02-06: Inputs: Added mapping for ImGuiKey_Space.

#include <stdint.h>     // uint64_t
#include <cstring>      // memcpy
#include "imgui.h"
#include "imgui_impl_allegro5.h"

// Allegro
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#ifdef _WIN32
#include <allegro5/allegro_windows.h>
#endif
#define ALLEGRO_HAS_CLIPBOARD   (ALLEGRO_VERSION_INT >= ((5 << 24) | (1 << 16) | (12 << 8)))    // Clipboard only supported from Allegro 5.1.12

// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#endif

// Data
static ALLEGRO_DISPLAY*         g_Display = NULL;
static ALLEGRO_BITMAP*          g_Texture = NULL;
static double                   g_Time = 0.0;
static ALLEGRO_MOUSE_CURSOR*    g_MouseCursorInvisible = NULL;
static ALLEGRO_VERTEX_DECL*     g_VertexDecl = NULL;
static char*                    g_ClipboardTextData = NULL;

struct ImDrawVertAllegro
{
    ImVec2 pos;
    ImVec2 uv;
    ALLEGRO_COLOR col;
};

// Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
{
    // Backup Allegro state that will be modified
    ALLEGRO_TRANSFORM last_transform = *al_get_current_transform();
    ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform();
    int last_clip_x, last_clip_y, last_clip_w, last_clip_h;
    al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h);
    int last_blender_op, last_blender_src, last_blender_dst;
    al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst);

    // Setup render state
    al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA);

    // Setup orthographic projection matrix
    // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
    {
        float L = draw_data->DisplayPos.x;
        float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
        float T = draw_data->DisplayPos.y;
        float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
        ALLEGRO_TRANSFORM transform;
        al_identity_transform(&transform);
        al_use_transform(&transform);
        al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f);
        al_use_projection_transform(&transform);
    }

    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];

        // Allegro's implementation of al_draw_indexed_prim() for DX9 is completely broken. Unindex our buffers ourselves.
        // FIXME-OPT: Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 float as well..
        static ImVector<ImDrawVertAllegro> vertices;
        vertices.resize(cmd_list->IdxBuffer.Size);
        for (int i = 0; i < cmd_list->IdxBuffer.Size; i++)
        {
            const ImDrawVert* src_v = &cmd_list->VtxBuffer[cmd_list->IdxBuffer[i]];
            ImDrawVertAllegro* dst_v = &vertices[i];
            dst_v->pos = src_v->pos;
            dst_v->uv = src_v->uv;
            unsigned char* c = (unsigned char*)&src_v->col;
            dst_v->col = al_map_rgba(c[0], c[1], c[2], c[3]);
        }

        const int* indices = NULL;
        if (sizeof(ImDrawIdx) == 2)
        {
            // FIXME-OPT: Unfortunately Allegro doesn't support 16-bit indices.. You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices.
            // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful.
            static ImVector<int> indices_converted;
            indices_converted.resize(cmd_list->IdxBuffer.Size);
            for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i)
                indices_converted[i] = (int)cmd_list->IdxBuffer.Data[i];
            indices = indices_converted.Data;
        }
        else if (sizeof(ImDrawIdx) == 4)
        {
            indices = (const int*)cmd_list->IdxBuffer.Data;
        }

        int idx_offset = 0;
        ImVec2 pos = draw_data->DisplayPos;
        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->TextureId;
                al_set_clipping_rectangle(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pcmd->ClipRect.x, pcmd->ClipRect.w - pcmd->ClipRect.y);
                al_draw_prim(&vertices[0], g_VertexDecl, texture, idx_offset, idx_offset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
            }
            idx_offset += pcmd->ElemCount;
        }
    }

    // Restore modified Allegro state
    al_set_blender(last_blender_op, last_blender_src, last_blender_dst);
    al_set_clipping_rectangle(last_clip_x, last_clip_y, last_clip_w, last_clip_h);
    al_use_transform(&last_transform);
    al_use_projection_transform(&last_projection_transform);
}

bool ImGui_ImplAllegro5_CreateDeviceObjects()
{
    // Build texture atlas
    ImGuiIO &io = ImGui::GetIO();
    unsigned char *pixels;
    int width, height;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

    // Create texture
    int flags = al_get_new_bitmap_flags();
    int fmt = al_get_new_bitmap_format();
    al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP|ALLEGRO_MIN_LINEAR|ALLEGRO_MAG_LINEAR);
    al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
    ALLEGRO_BITMAP* img = al_create_bitmap(width, height);
    al_set_new_bitmap_flags(flags);
    al_set_new_bitmap_format(fmt);
    if (!img)
        return false;

    ALLEGRO_LOCKED_REGION *locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY);
    if (!locked_img)
    {
        al_destroy_bitmap(img);
        return false;
    }
    memcpy(locked_img->data, pixels, sizeof(int)*width*height);
    al_unlock_bitmap(img);

    // Convert software texture to hardware texture.
    ALLEGRO_BITMAP* cloned_img = al_clone_bitmap(img);
    al_destroy_bitmap(img);
    if (!cloned_img)
        return false;

    // Store our identifier
    io.Fonts->TexID = (void*)cloned_img;
    g_Texture = cloned_img;

    // Create an invisible mouse cursor
    // Because al_hide_mouse_cursor() seems to mess up with the actual inputs..
    ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8,8);
    g_MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0);
    al_destroy_bitmap(mouse_cursor);

    return true;
}

void ImGui_ImplAllegro5_InvalidateDeviceObjects()
{
    if (g_Texture)
    {
        al_destroy_bitmap(g_Texture);
        ImGui::GetIO().Fonts->TexID = NULL;
        g_Texture = NULL;
    }
    if (g_MouseCursorInvisible)
    {
        al_destroy_mouse_cursor(g_MouseCursorInvisible);
        g_MouseCursorInvisible = NULL;
    }
}

#if ALLEGRO_HAS_CLIPBOARD
static const char* ImGui_ImplAllegro5_GetClipboardText(void*)
{
    if (g_ClipboardTextData)
        al_free(g_ClipboardTextData);
    g_ClipboardTextData = al_get_clipboard_text(g_Display);
    return g_ClipboardTextData;
}

static void ImGui_ImplAllegro5_SetClipboardText(void*, const char* text)
{
    al_set_clipboard_text(g_Display, text);
}
#endif

bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
{
    g_Display = display;

    // Setup back-end capabilities flags
    ImGuiIO& io = ImGui::GetIO();
    io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;       // We can honor GetMouseCursor() values (optional)

    // Create custom vertex declaration.
    // Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats.
    // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
    ALLEGRO_VERTEX_ELEMENT elems[] =
    {
        { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) },
        { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) },
        { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) },
        { 0, 0, 0 }
    };
    g_VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));

    io.KeyMap[ImGuiKey_Tab] = ALLEGRO_KEY_TAB;
    io.KeyMap[ImGuiKey_LeftArrow] = ALLEGRO_KEY_LEFT;
    io.KeyMap[ImGuiKey_RightArrow] = ALLEGRO_KEY_RIGHT;
    io.KeyMap[ImGuiKey_UpArrow] = ALLEGRO_KEY_UP;
    io.KeyMap[ImGuiKey_DownArrow] = ALLEGRO_KEY_DOWN;
    io.KeyMap[ImGuiKey_PageUp] = ALLEGRO_KEY_PGUP;
    io.KeyMap[ImGuiKey_PageDown] = ALLEGRO_KEY_PGDN;
    io.KeyMap[ImGuiKey_Home] = ALLEGRO_KEY_HOME;
    io.KeyMap[ImGuiKey_End] = ALLEGRO_KEY_END;
    io.KeyMap[ImGuiKey_Insert] = ALLEGRO_KEY_INSERT;
    io.KeyMap[ImGuiKey_Delete] = ALLEGRO_KEY_DELETE;
    io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE;
    io.KeyMap[ImGuiKey_Space] = ALLEGRO_KEY_SPACE;
    io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER;
    io.KeyMap[ImGuiKey_Escape] = ALLEGRO_KEY_ESCAPE;
    io.KeyMap[ImGuiKey_A] = ALLEGRO_KEY_A;
    io.KeyMap[ImGuiKey_C] = ALLEGRO_KEY_C;
    io.KeyMap[ImGuiKey_V] = ALLEGRO_KEY_V;
    io.KeyMap[ImGuiKey_X] = ALLEGRO_KEY_X;
    io.KeyMap[ImGuiKey_Y] = ALLEGRO_KEY_Y;
    io.KeyMap[ImGuiKey_Z] = ALLEGRO_KEY_Z;

#if ALLEGRO_HAS_CLIPBOARD
    io.SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText;
    io.GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText;
    io.ClipboardUserData = NULL;
#endif

    return true;
}

void ImGui_ImplAllegro5_Shutdown()
{
    ImGui_ImplAllegro5_InvalidateDeviceObjects();
    g_Display = NULL;

    // Destroy last known clipboard data
    if (g_ClipboardTextData)
        al_free(g_ClipboardTextData);
    g_ClipboardTextData = NULL;
}

// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - 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.
bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev)
{
    ImGuiIO& io = ImGui::GetIO();

    switch (ev->type)
    {
    case ALLEGRO_EVENT_MOUSE_AXES:
        io.MouseWheel += ev->mouse.dz;
        io.MouseWheelH += ev->mouse.dw;
        return true;
    case ALLEGRO_EVENT_KEY_CHAR:
        if (ev->keyboard.display == g_Display)
            if (ev->keyboard.unichar > 0 && ev->keyboard.unichar < 0x10000)
                io.AddInputCharacter((unsigned short)ev->keyboard.unichar);
        return true;
    case ALLEGRO_EVENT_KEY_DOWN:
    case ALLEGRO_EVENT_KEY_UP:
        if (ev->keyboard.display == g_Display)
            io.KeysDown[ev->keyboard.keycode] = (ev->type == ALLEGRO_EVENT_KEY_DOWN);
        return true;
    }
    return false;
}

static void ImGui_ImplAllegro5_UpdateMouseCursor()
{
    ImGuiIO& io = ImGui::GetIO();
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
        return;

    ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
    if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
    {
        // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
        al_set_mouse_cursor(g_Display, g_MouseCursorInvisible);
    }
    else
    {
        ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
        switch (imgui_cursor)
        {
        case ImGuiMouseCursor_TextInput:    cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
        case ImGuiMouseCursor_ResizeAll:    cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
        case ImGuiMouseCursor_ResizeNS:     cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
        case ImGuiMouseCursor_ResizeEW:     cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
        case ImGuiMouseCursor_ResizeNESW:   cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
        case ImGuiMouseCursor_ResizeNWSE:   cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
        }
        al_set_system_mouse_cursor(g_Display, cursor_id);
    }
}

void ImGui_ImplAllegro5_NewFrame()
{
    if (!g_Texture)
        ImGui_ImplAllegro5_CreateDeviceObjects();

    ImGuiIO &io = ImGui::GetIO();

    // Setup display size (every frame to accommodate for window resizing)
    int w, h;
    w = al_get_display_width(g_Display);
    h = al_get_display_height(g_Display);
    io.DisplaySize = ImVec2((float)w, (float)h);

    // Setup time step
    double current_time = al_get_time();
    io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
    g_Time = current_time;

    // Setup inputs
    ALLEGRO_KEYBOARD_STATE keys;
    al_get_keyboard_state(&keys);
    io.KeyCtrl = al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL);
    io.KeyShift = al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT);
    io.KeyAlt = al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR);
    io.KeySuper = al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN);

    ALLEGRO_MOUSE_STATE mouse;
    if (keys.display == g_Display)
    {
        al_get_mouse_state(&mouse);
        io.MousePos = ImVec2((float)mouse.x, (float)mouse.y);
    }
    else
    {
        io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
    }

    al_get_mouse_state(&mouse);
    io.MouseDown[0] = mouse.buttons & (1 << 0);
    io.MouseDown[1] = mouse.buttons & (1 << 1);
    io.MouseDown[2] = mouse.buttons & (1 << 2);

    ImGui_ImplAllegro5_UpdateMouseCursor();
}