Bläddra i källkod

Add flip_world from https://github.com/jblanked/FlipWorld

git-subtree-dir: flip_world
git-subtree-mainline: 29bcaeec3e39fe8eed96c29ff34184c850b4b703
git-subtree-split: 5f68cbe30cce31bb85f434d10fff9841ebae9815
WillyJL 8 månader sedan
förälder
incheckning
cdde3670b6
100 ändrade filer med 7610 tillägg och 0 borttagningar
  1. 1 0
      flip_world/.gitsubtree
  2. 92 0
      flip_world/alloc/alloc.c
  3. 9 0
      flip_world/alloc/alloc.h
  4. 79 0
      flip_world/app.c
  5. BIN
      flip_world/app.png
  6. 21 0
      flip_world/application.fam
  7. BIN
      flip_world/assets/01-home.png
  8. BIN
      flip_world/assets/02-town.png
  9. BIN
      flip_world/assets/03-town.png
  10. BIN
      flip_world/assets/04-town.png
  11. BIN
      flip_world/assets/05-tree.png
  12. BIN
      flip_world/assets/06-tree.png
  13. 67 0
      flip_world/assets/CHANGELOG.md
  14. BIN
      flip_world/assets/KeyBackspaceSelected_16x9.png
  15. BIN
      flip_world/assets/KeyBackspace_16x9.png
  16. BIN
      flip_world/assets/KeySaveSelected_24x11.png
  17. BIN
      flip_world/assets/KeySave_24x11.png
  18. 66 0
      flip_world/assets/README.md
  19. BIN
      flip_world/assets/WarningDolphin_45x42.png
  20. BIN
      flip_world/assets/icon_fence_16x8px.png
  21. BIN
      flip_world/assets/icon_fence_end_16x8px.png
  22. BIN
      flip_world/assets/icon_fence_vertical_end_6x8px.png
  23. BIN
      flip_world/assets/icon_fence_vertical_start_6x15px.png
  24. BIN
      flip_world/assets/icon_flower_16x16.png
  25. BIN
      flip_world/assets/icon_house_48x32px.png
  26. BIN
      flip_world/assets/icon_lake_bottom_31x12px.png
  27. BIN
      flip_world/assets/icon_lake_bottom_left_24x22px.png
  28. BIN
      flip_world/assets/icon_lake_bottom_right_24x22px.png
  29. BIN
      flip_world/assets/icon_lake_left_11x31px.png
  30. BIN
      flip_world/assets/icon_lake_right_11x31.png
  31. BIN
      flip_world/assets/icon_lake_top_31x12px.png
  32. BIN
      flip_world/assets/icon_lake_top_left_24x22px.png
  33. BIN
      flip_world/assets/icon_lake_top_right_24x22px.png
  34. BIN
      flip_world/assets/icon_man_7x16.png
  35. BIN
      flip_world/assets/icon_menu_128x64px.png
  36. BIN
      flip_world/assets/icon_plant_16x16.png
  37. BIN
      flip_world/assets/icon_rock_large_18x19px.png
  38. BIN
      flip_world/assets/icon_rock_medium_16x14px.png
  39. BIN
      flip_world/assets/icon_rock_small_10x8px.png
  40. BIN
      flip_world/assets/icon_sword_10x10px.png
  41. BIN
      flip_world/assets/icon_tree_16x16.png
  42. BIN
      flip_world/assets/icon_woman_9x16.png
  43. BIN
      flip_world/assets/icon_world_change_128x64px.png
  44. 398 0
      flip_world/callback/alloc.c
  45. 9 0
      flip_world/callback/alloc.h
  46. 628 0
      flip_world/callback/callback.c
  47. 21 0
      flip_world/callback/callback.h
  48. 192 0
      flip_world/callback/free.c
  49. 9 0
      flip_world/callback/free.h
  50. 1174 0
      flip_world/callback/game.c
  51. 21 0
      flip_world/callback/game.h
  52. 590 0
      flip_world/callback/loader.c
  53. 39 0
      flip_world/callback/loader.h
  54. 25 0
      flip_world/callback/utils.h
  55. 626 0
      flip_world/easy_flipper/easy_flipper.c
  56. 296 0
      flip_world/easy_flipper/easy_flipper.h
  57. 674 0
      flip_world/engine/LICENSE
  58. 28 0
      flip_world/engine/canvas.c
  59. 32 0
      flip_world/engine/canvas.h
  60. 53 0
      flip_world/engine/clock_timer.c
  61. 15 0
      flip_world/engine/clock_timer.h
  62. 27 0
      flip_world/engine/engine.h
  63. 217 0
      flip_world/engine/entity.c
  64. 65 0
      flip_world/engine/entity.h
  65. 58 0
      flip_world/engine/entity_i.h
  66. 199 0
      flip_world/engine/game_engine.c
  67. 88 0
      flip_world/engine/game_engine.h
  68. 162 0
      flip_world/engine/game_manager.c
  69. 40 0
      flip_world/engine/game_manager.h
  70. 24 0
      flip_world/engine/game_manager_i.h
  71. 214 0
      flip_world/engine/level.c
  72. 63 0
      flip_world/engine/level.h
  73. 26 0
      flip_world/engine/level_i.h
  74. 59 0
      flip_world/engine/main.c
  75. 84 0
      flip_world/engine/scripts/sprite_builder.py
  76. 297 0
      flip_world/engine/sensors/ICM42688P/ICM42688P.c
  77. 127 0
      flip_world/engine/sensors/ICM42688P/ICM42688P.h
  78. 176 0
      flip_world/engine/sensors/ICM42688P/ICM42688P_regs.h
  79. 326 0
      flip_world/engine/sensors/imu.c
  80. 15 0
      flip_world/engine/sensors/imu.h
  81. 69 0
      flip_world/engine/sprite.c
  82. 44 0
      flip_world/engine/sprite.h
  83. 33 0
      flip_world/engine/vector.c
  84. 32 0
      flip_world/engine/vector.h
  85. BIN
      flip_world/file_assets/sprites/enemy_left_cyclops_10x11px.fxbm
  86. BIN
      flip_world/file_assets/sprites/enemy_left_ghost_15x15px.fxbm
  87. BIN
      flip_world/file_assets/sprites/enemy_left_ogre_10x13px.fxbm
  88. BIN
      flip_world/file_assets/sprites/enemy_right_cyclops_10x11px.fxbm
  89. BIN
      flip_world/file_assets/sprites/enemy_right_ghost_15x15px.fxbm
  90. BIN
      flip_world/file_assets/sprites/enemy_right_ogre_10x13px.fxbm
  91. BIN
      flip_world/file_assets/sprites/npc_left_funny_15x21px.fxbm
  92. BIN
      flip_world/file_assets/sprites/npc_right_funny_15x21px.fxbm
  93. BIN
      flip_world/file_assets/sprites/player_left_axe_15x11px.fxbm
  94. BIN
      flip_world/file_assets/sprites/player_left_bow_13x11px.fxbm
  95. BIN
      flip_world/file_assets/sprites/player_left_naked_10x10px.fxbm
  96. BIN
      flip_world/file_assets/sprites/player_left_sword_15x11px.fxbm
  97. BIN
      flip_world/file_assets/sprites/player_right_axe_15x11px.fxbm
  98. BIN
      flip_world/file_assets/sprites/player_right_bow_13x11.fxbm
  99. BIN
      flip_world/file_assets/sprites/player_right_naked_10x10px.fxbm
  100. BIN
      flip_world/file_assets/sprites/player_right_sword_15x11px.fxbm

+ 1 - 0
flip_world/.gitsubtree

@@ -0,0 +1 @@
+https://github.com/jblanked/FlipWorld main FlipperZero/src 2620e0f3c9a13bf1042854ae04b739223128fa39

+ 92 - 0
flip_world/alloc/alloc.c

@@ -0,0 +1,92 @@
+#include <alloc/alloc.h>
+#include <callback/callback.h>
+#include <callback/loader.h>
+#include <callback/free.h>
+
+uint32_t callback_exit_app(void *context)
+{
+    UNUSED(context);
+    return VIEW_NONE;
+}
+
+uint32_t callback_to_submenu(void *context)
+{
+    UNUSED(context);
+    return FlipWorldViewSubmenu;
+}
+
+uint32_t callback_to_wifi_settings(void *context)
+{
+    UNUSED(context);
+    return FlipWorldViewVariableItemList;
+}
+uint32_t callback_to_settings(void *context)
+{
+    UNUSED(context);
+    return FlipWorldViewSubmenuOther;
+}
+
+void *global_app;
+void flip_world_show_submenu()
+{
+    FlipWorldApp *app = (FlipWorldApp *)global_app;
+    if (app->submenu)
+    {
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+    }
+}
+
+// Function to allocate resources for the FlipWorldApp
+FlipWorldApp *flip_world_app_alloc()
+{
+    FlipWorldApp *app = (FlipWorldApp *)malloc(sizeof(FlipWorldApp));
+    global_app = app;
+
+    Gui *gui = furi_record_open(RECORD_GUI);
+
+    // Allocate ViewDispatcher
+    if (!easy_flipper_set_view_dispatcher(&app->view_dispatcher, gui, app))
+    {
+        return NULL;
+    }
+
+    // Submenu
+    if (!easy_flipper_set_submenu(&app->submenu, FlipWorldViewSubmenu, VERSION_TAG, callback_exit_app, &app->view_dispatcher))
+    {
+        return NULL;
+    }
+
+    submenu_add_item(app->submenu, "Play", FlipWorldSubmenuIndexGameSubmenu, callback_submenu_choices, app);
+    submenu_add_item(app->submenu, "About", FlipWorldSubmenuIndexMessage, callback_submenu_choices, app);
+    submenu_add_item(app->submenu, "Settings", FlipWorldSubmenuIndexSettings, callback_submenu_choices, app);
+
+    // Switch to the main view
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+
+    return app;
+}
+
+// Function to free the resources used by FlipWorldApp
+void flip_world_app_free(FlipWorldApp *app)
+{
+    furi_check(app, "FlipWorldApp is NULL");
+
+    // Free Submenu(s)
+    if (app->submenu)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewSubmenu);
+        submenu_free(app->submenu);
+    }
+
+    free_all_views(app, true, true, true);
+
+    // free the view dispatcher
+    view_dispatcher_free(app->view_dispatcher);
+
+    // close the gui
+    furi_record_close(RECORD_GUI);
+
+    // free the app
+    if (app)
+        free(app);
+}

+ 9 - 0
flip_world/alloc/alloc.h

@@ -0,0 +1,9 @@
+#pragma once
+#include <flip_world.h>
+FlipWorldApp *flip_world_app_alloc();
+void flip_world_app_free(FlipWorldApp *app);
+void flip_world_show_submenu();
+uint32_t callback_exit_app(void *context);
+uint32_t callback_to_submenu(void *context);
+uint32_t callback_to_wifi_settings(void *context);
+uint32_t callback_to_settings(void *context);

+ 79 - 0
flip_world/app.c

@@ -0,0 +1,79 @@
+#include <alloc/alloc.h>
+#include <flip_storage/storage.h>
+#include <update/update.h>
+
+// Entry point for the FlipWorld application
+int32_t flip_world_main(void *p)
+{
+    // check memory
+    if (!is_enough_heap(sizeof(FlipWorldApp) + sizeof(FlipperHTTP), true))
+    {
+        easy_flipper_dialog("Memory Error", "Not enough heap memory.\nPlease restart your Flipper Zero.");
+        return 0; // return success so the user can see the error
+    }
+
+    // Suppress unused parameter warning
+    UNUSED(p);
+
+    // Initialize the FlipWorld application
+    FlipWorldApp *app = flip_world_app_alloc();
+    if (!app)
+        return -1;
+
+    // initialize the VGM
+    furi_hal_gpio_init_simple(&gpio_ext_pc1, GpioModeOutputPushPull);
+    furi_hal_gpio_write(&gpio_ext_pc1, false); // pull pin 15 low
+
+    // check if board is connected (Derek Jamison)
+    FlipperHTTP *fhttp = flipper_http_alloc();
+    if (!fhttp)
+    {
+        easy_flipper_dialog("FlipperHTTP Error", "The UART is likely busy.\nEnsure you have the correct\nflash for your board then\nrestart your Flipper Zero.");
+        return -1;
+    }
+
+    save_char("app_version", VERSION);
+
+    if (!flipper_http_send_command(fhttp, HTTP_CMD_PING))
+    {
+        FURI_LOG_E(TAG, "Failed to ping the device");
+        flipper_http_free(fhttp);
+        return -1;
+    }
+
+    furi_delay_ms(100);
+
+    // Try to wait for pong response.
+    uint32_t counter = 10;
+    while (fhttp->state == INACTIVE && --counter > 0)
+    {
+        FURI_LOG_D(TAG, "Waiting for PONG");
+        furi_delay_ms(100);
+    }
+
+    // last response should be PONG
+    if (!fhttp->last_response || strcmp(fhttp->last_response, "[PONG]") != 0)
+    {
+        easy_flipper_dialog("FlipperHTTP Error", "Ensure your WiFi Developer\nBoard or Pico W is connected\nand the latest FlipperHTTP\nfirmware is installed.");
+        FURI_LOG_E(TAG, "Failed to receive PONG");
+    }
+    else
+    {
+        // for now use the catalog API until I implement caching on the server
+        if (update_is_ready(fhttp, true))
+        {
+            easy_flipper_dialog("Update Status", "Complete.\nRestart your Flipper Zero.");
+        }
+    }
+
+    flipper_http_free(fhttp);
+
+    // Run the view dispatcher
+    view_dispatcher_run(app->view_dispatcher);
+
+    // Free the resources used by the FlipWorld application
+    flip_world_app_free(app);
+
+    // Return 0 to indicate success
+    return 0;
+}

BIN
flip_world/app.png


+ 21 - 0
flip_world/application.fam

@@ -0,0 +1,21 @@
+App(
+    appid="flip_world",
+    name="FlipWorld",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="flip_world_main",
+    stack_size=4 * 1024,
+    fap_icon="app.png",
+    fap_category="GPIO",
+    fap_description="The first open-world multiplayer game, best played with the VGM.", 
+    fap_icon_assets="assets",
+    fap_file_assets="file_assets", 
+    fap_extbuild=(
+        ExtFile(
+            path="${FAP_SRC_DIR}/file_assets",
+            command="${PYTHON3} ${FAP_SRC_DIR}/engine/scripts/sprite_builder.py ${FAP_SRC_DIR.abspath}/sprites ${TARGET.abspath}/sprites",
+        ),
+    ),
+    fap_author="JBlanked",
+    fap_weburl="https://github.com/jblanked/FlipWorld",
+    fap_version="0.8.3",
+)

BIN
flip_world/assets/01-home.png


BIN
flip_world/assets/02-town.png


BIN
flip_world/assets/03-town.png


BIN
flip_world/assets/04-town.png


BIN
flip_world/assets/05-tree.png


BIN
flip_world/assets/06-tree.png


+ 67 - 0
flip_world/assets/CHANGELOG.md

@@ -0,0 +1,67 @@
+## 0.8.3 (2025-04-24)
+- Added PVE multiplayer (up to 5 users per game).
+- Added a level requirement to play multiplayer.
+- Updated to the latest auto-update library.
+- Fixed world transitions.
+- Updated game ending responses.
+
+## 0.8.2 (2025-04-19)
+- Fixed an out-of-memory crash.
+
+## 0.8.1 (2025-04-09)
+- Improved memory allocation, saving 26 KB.
+- Added auto-updating (currently uses the catalog API).
+- Major code refactoring.
+
+## 0.8 (2025-04-05)
+- Improved memory allocation.
+- Added multiplayer support.
+- Updated the default settings for vibration and sound.
+
+## 0.7 (2025-03-21)
+- Sped up player movement.
+- Added tutorial mode.
+- Fixed issues with transitioning between worlds.
+
+## 0.6.1 (2025-03-15)
+- Switched the server backend in preparation for multiplayer features introduced in version 0.8.
+
+## 0.6 (2025-03-10)
+- Fixed saving of player attributes to ensure they are stored as intended.
+- Updated the player's level and strength progression with XP increases.
+- Started implementing multiplayer (requires FlipperHTTP v1.7).
+- Fixed the display of user stats when switching worlds.
+
+## 0.5 (2025-01-31)
+- Fixed errors with saving.
+- Improved memory allocation.
+- Added NPCs.
+
+## 0.4 (2025-01-23)
+- Added an in-game menu.
+- Added new controls: hold OK to access the in-game menu, press BACK to exit the menu, and hold BACK to exit the game.
+- Added an option to choose the player's weapon in the game settings.
+- Added a transition icon for switching worlds.
+- Doubled the size of each world (from 384x192 to 768x384).
+- Improved memory allocation.
+
+## 0.3 (2025-01-14)
+- Added new worlds.
+- Improved memory allocation.
+- Updated API integration for loading and saving player attributes.
+- Upgraded FlipperHTTP to the latest version.
+
+## 0.2 (2025-01-02)
+- Added support for the Video Game Module (requires FlipperHTTP flash).
+- Introduced various enemy types to enhance gameplay.
+- Added features for player health, XP, level, health regeneration, attack, and strength.
+- Implemented vibration, sound, and LED notifications when a player is attacking or being attacked.
+- Displayed the player's username above the character and continuously showed health, XP, and level in the bottom-left corner of the screen.
+- Updated all game icons for improved visual appeal.
+- Upgraded to the latest version of the FlipperHTTP library.
+- Revised toggles in the game settings to ensure they work as intended.
+- Improved collision mechanics for more accurate interactions.
+- Updated the default icon representing the player's character.
+
+## 0.1 (2024-12-21)
+- Initial release.

BIN
flip_world/assets/KeyBackspaceSelected_16x9.png


BIN
flip_world/assets/KeyBackspace_16x9.png


BIN
flip_world/assets/KeySaveSelected_24x11.png


BIN
flip_world/assets/KeySave_24x11.png


+ 66 - 0
flip_world/assets/README.md

@@ -0,0 +1,66 @@
+The first open-world multiplayer game for the Flipper Zero, best played with the VGM. Here's a video tutorial: https://www.youtube.com/watch?v=Qp7qmYMfdUA
+
+## Connect Online
+- Discord: https://discord.gg/5aN9qwkEc6
+- YouTube: https://www.youtube.com/@jblanked
+- Instagram: https://www.instagram.com/jblanked
+- Other: https://www.jblanked.com/social/
+
+## Requirements
+- WiFi Developer Board, Raspberry Pi, or ESP32 device flashed with FlipperHTTP v1.8.2 or higher: https://github.com/jblanked/FlipperHTTP
+- 2.4 GHz WiFi access point
+
+## How It Works
+
+FlipWorld and FlipSocial are connected. Your login information is the same in both apps; if you register an account in either app, you can log in to both using that information. This also means that your friends, messages, and achievements are synced between apps. You only need a username and password to start, which are set in the User Settings. Keep in mind your username will be displayed to others, so choose wisely.
+
+**Settings**
+
+- **WiFi**: Enter your SSID and password to connect to your 2.4 GHz network.
+- **User**: Add or update your username and password (this is the same login information as your FlipSocial account).
+- **Game**: Install the Official World Pack, choose your weapon, set your FPS (30, 60, 120, or 240), and select whether you want the screen backlight to always be on, the sound to be on, and the vibration to be on.
+
+**Controls**
+
+- **Press/Hold LEFT**: Turn left if not already facing left, then walk left if the button is still pressed.
+- **Press/Hold RIGHT**: Turn right if not already facing right, then walk right if the button is still pressed.
+- **Press/Hold UP**: Walk up.
+- **Press/Hold DOWN**: Walk down.
+- **Press OK**: Interact, attack, or teleport. Attacks enemies when colliding with them until all enemies are defeated. Interacts with NPCs when colliding with them.
+- **HOLD OK**: In-Game Menu.
+- **Press BACK**: Leave the menu.
+- **HOLD BACK**: Exit the game.
+
+**Player Attributes**
+
+- **Health**: The amount of life points the player has.
+- **XP**: The amount of experience points the player has.
+- **Level**: The rank/level of the player.
+- **Strength**: The attack power of the player's attacks.
+- **Health Regeneration**: The amount of health a player gains per second.
+- **Attack Timer**: The duration the player must wait between attacks.
+
+As a new player, you have 100 health, 0 XP, 10 strength, 1 health regeneration, an attack timer of 1, and are level 1. Each level, the player gains an extra 1 strength and 10 health. Additionally, the amount of XP needed to level up increases exponentially by 1.5. For example, to reach level 2, you need 100 XP; for level 3, 150 XP; for level 4, 225 XP; and so on.
+
+**Enemies**
+
+Enemies have similar attributes to players but do not have XP or health regeneration. For example, level 1 enemies have 100 health and 10 strength, just like a level 1 player.
+
+**Attacks**
+
+If an enemy attacks you, your health decreases by the enemy's strength (attack power). Additionally, if an enemy defeats you, your XP decreases by the enemy's strength. Conversely, when you successfully attack an enemy, you gain health equal to 10% of the enemy's strength and increase your XP by the enemy's full strength.
+
+An enemy attack registers if the enemy is facing you and collides with you. However, to attack an enemy successfully, the enemy must be facing away from you, and you must collide with them while pressing "OK".
+
+**NPCs**
+
+NPCs are friendly characters that players can interact with. Currently, you can interact with them by clicking "OK" while colliding with them.
+
+## Short Tutorial
+
+1. Ensure your WiFi Developer Board and Video Game Module are flashed with FlipperHTTP.
+2. Install the app.
+3. Restart your Flipper Zero, then open FlipWorld.
+4. Click "Settings -> WiFi", then input your WiFi SSID and password.
+5. Hit the "BACK" button, click "User". If your username is not present, click "Username" and add one. Do the same for the password field.
+6. Go back to the main menu and hit "Play", followed by "Tutorial". It will register an account if necessary and fetch data from our API that's used to render our graphics.

BIN
flip_world/assets/WarningDolphin_45x42.png


BIN
flip_world/assets/icon_fence_16x8px.png


BIN
flip_world/assets/icon_fence_end_16x8px.png


BIN
flip_world/assets/icon_fence_vertical_end_6x8px.png


BIN
flip_world/assets/icon_fence_vertical_start_6x15px.png


BIN
flip_world/assets/icon_flower_16x16.png


BIN
flip_world/assets/icon_house_48x32px.png


BIN
flip_world/assets/icon_lake_bottom_31x12px.png


BIN
flip_world/assets/icon_lake_bottom_left_24x22px.png


BIN
flip_world/assets/icon_lake_bottom_right_24x22px.png


BIN
flip_world/assets/icon_lake_left_11x31px.png


BIN
flip_world/assets/icon_lake_right_11x31.png


BIN
flip_world/assets/icon_lake_top_31x12px.png


BIN
flip_world/assets/icon_lake_top_left_24x22px.png


BIN
flip_world/assets/icon_lake_top_right_24x22px.png


BIN
flip_world/assets/icon_man_7x16.png


BIN
flip_world/assets/icon_menu_128x64px.png


BIN
flip_world/assets/icon_plant_16x16.png


BIN
flip_world/assets/icon_rock_large_18x19px.png


BIN
flip_world/assets/icon_rock_medium_16x14px.png


BIN
flip_world/assets/icon_rock_small_10x8px.png


BIN
flip_world/assets/icon_sword_10x10px.png


BIN
flip_world/assets/icon_tree_16x16.png


BIN
flip_world/assets/icon_woman_9x16.png


BIN
flip_world/assets/icon_world_change_128x64px.png


+ 398 - 0
flip_world/callback/alloc.c

@@ -0,0 +1,398 @@
+#include "callback/alloc.h"
+#include "alloc/alloc.h"
+#include "callback/callback.h"
+#include <flip_storage/storage.h>
+
+bool alloc_message_view(void *context, MessageState state)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->view_message)
+    {
+        FURI_LOG_E(TAG, "Message view already allocated");
+        return false;
+    }
+    switch (state)
+    {
+    case MessageStateAbout:
+        easy_flipper_set_view(&app->view_message, FlipWorldViewMessage, callback_message_draw, NULL, callback_to_submenu, &app->view_dispatcher, app);
+        break;
+    case MessageStateLoading:
+        easy_flipper_set_view(&app->view_message, FlipWorldViewMessage, callback_message_draw, NULL, NULL, &app->view_dispatcher, app);
+        break;
+    case MessageStateWaitingLobby:
+        easy_flipper_set_view(&app->view_message, FlipWorldViewMessage, callback_message_draw, callback_message_input, NULL, &app->view_dispatcher, app);
+        break;
+    }
+    if (!app->view_message)
+    {
+        FURI_LOG_E(TAG, "Failed to allocate message view");
+        return false;
+    }
+    view_allocate_model(app->view_message, ViewModelTypeLockFree, sizeof(MessageModel));
+    MessageModel *model = view_get_model(app->view_message);
+    model->message_state = state;
+    return true;
+}
+
+bool alloc_text_input_view(void *context, char *title)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (!title)
+    {
+        FURI_LOG_E(TAG, "Title is NULL");
+        return false;
+    }
+    app->text_input_buffer_size = 64;
+    if (!app->text_input_buffer)
+    {
+        if (!easy_flipper_set_buffer(&app->text_input_buffer, app->text_input_buffer_size))
+        {
+            return false;
+        }
+    }
+    if (!app->text_input_temp_buffer)
+    {
+        if (!easy_flipper_set_buffer(&app->text_input_temp_buffer, app->text_input_buffer_size))
+        {
+            return false;
+        }
+    }
+    if (!app->text_input)
+    {
+        if (!easy_flipper_set_uart_text_input(
+                &app->text_input,
+                FlipWorldViewTextInput,
+                title,
+                app->text_input_temp_buffer,
+                app->text_input_buffer_size,
+                is_str(title, "SSID") ? callback_updated_wifi_ssid : is_str(title, "Password")     ? callback_updated_wifi_pass
+                                                                 : is_str(title, "Username-Login") ? callback_updated_username
+                                                                                                   : callback_updated_password,
+                callback_to_wifi_settings,
+                &app->view_dispatcher,
+                app))
+        {
+            return false;
+        }
+        if (!app->text_input)
+        {
+            return false;
+        }
+        char ssid[64];
+        char pass[64];
+        char username[64];
+        char password[64];
+        if (load_settings(ssid, sizeof(ssid), pass, sizeof(pass), username, sizeof(username), password, sizeof(password)))
+        {
+            if (is_str(title, "SSID"))
+            {
+                strncpy(app->text_input_temp_buffer, ssid, app->text_input_buffer_size);
+            }
+            else if (is_str(title, "Password"))
+            {
+                strncpy(app->text_input_temp_buffer, pass, app->text_input_buffer_size);
+            }
+            else if (is_str(title, "Username-Login"))
+            {
+                strncpy(app->text_input_temp_buffer, username, app->text_input_buffer_size);
+            }
+            else if (is_str(title, "Password-Login"))
+            {
+                strncpy(app->text_input_temp_buffer, password, app->text_input_buffer_size);
+            }
+        }
+    }
+    return true;
+}
+bool alloc_variable_item_list(void *context, uint32_t view_id)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    char ssid[64];
+    char pass[64];
+    char username[64];
+    char password[64];
+    if (!app->variable_item_list)
+    {
+        switch (view_id)
+        {
+        case FlipWorldSubmenuIndexWiFiSettings:
+            if (!easy_flipper_set_variable_item_list(&app->variable_item_list, FlipWorldViewVariableItemList, callback_wifi_settings_select, callback_to_settings, &app->view_dispatcher, app))
+            {
+                FURI_LOG_E(TAG, "Failed to allocate variable item list");
+                return false;
+            }
+
+            if (!app->variable_item_list)
+            {
+                FURI_LOG_E(TAG, "Variable item list is NULL");
+                return false;
+            }
+
+            if (!app->variable_item_wifi_ssid)
+            {
+                app->variable_item_wifi_ssid = variable_item_list_add(app->variable_item_list, "SSID", 0, NULL, NULL);
+                variable_item_set_current_value_text(app->variable_item_wifi_ssid, "");
+            }
+            if (!app->variable_item_wifi_pass)
+            {
+                app->variable_item_wifi_pass = variable_item_list_add(app->variable_item_list, "Password", 0, NULL, NULL);
+                variable_item_set_current_value_text(app->variable_item_wifi_pass, "");
+            }
+            if (load_settings(ssid, sizeof(ssid), pass, sizeof(pass), username, sizeof(username), password, sizeof(password)))
+            {
+                variable_item_set_current_value_text(app->variable_item_wifi_ssid, ssid);
+                // variable_item_set_current_value_text(app->variable_item_wifi_pass, pass);
+                save_char("WiFi-SSID", ssid);
+                save_char("WiFi-Password", pass);
+                save_char("Flip-Social-Username", username);
+                save_char("Flip-Social-Password", password);
+            }
+            break;
+        case FlipWorldSubmenuIndexGameSettings:
+            if (!easy_flipper_set_variable_item_list(&app->variable_item_list, FlipWorldViewVariableItemList, callback_game_settings_select, callback_to_settings, &app->view_dispatcher, app))
+            {
+                FURI_LOG_E(TAG, "Failed to allocate variable item list");
+                return false;
+            }
+
+            if (!app->variable_item_list)
+            {
+                FURI_LOG_E(TAG, "Variable item list is NULL");
+                return false;
+            }
+
+            if (!app->variable_item_game_download_world)
+            {
+                app->variable_item_game_download_world = variable_item_list_add(app->variable_item_list, "Install Official World Pack", 0, NULL, NULL);
+                variable_item_set_current_value_text(app->variable_item_game_download_world, "");
+            }
+            if (!app->variable_item_game_player_sprite)
+            {
+                app->variable_item_game_player_sprite = variable_item_list_add(app->variable_item_list, "Weapon", 4, callback_player_on_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_player_sprite, 1);
+                variable_item_set_current_value_text(app->variable_item_game_player_sprite, player_sprite_choices[1]);
+            }
+            if (!app->variable_item_game_fps)
+            {
+                app->variable_item_game_fps = variable_item_list_add(app->variable_item_list, "FPS", 4, callback_fps_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_fps, 0);
+                variable_item_set_current_value_text(app->variable_item_game_fps, fps_choices_str[0]);
+            }
+            if (!app->variable_item_game_vgm_x)
+            {
+                app->variable_item_game_vgm_x = variable_item_list_add(app->variable_item_list, "VGM Horizontal", 12, callback_vgm_x_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_vgm_x, 2);
+                variable_item_set_current_value_text(app->variable_item_game_vgm_x, vgm_levels[2]);
+            }
+            if (!app->variable_item_game_vgm_y)
+            {
+                app->variable_item_game_vgm_y = variable_item_list_add(app->variable_item_list, "VGM Vertical", 12, callback_vgm_y_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_vgm_y, 2);
+                variable_item_set_current_value_text(app->variable_item_game_vgm_y, vgm_levels[2]);
+            }
+            if (!app->variable_item_game_screen_always_on)
+            {
+                app->variable_item_game_screen_always_on = variable_item_list_add(app->variable_item_list, "Keep Screen On?", 2, callback_screen_on_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_screen_always_on, 1);
+                variable_item_set_current_value_text(app->variable_item_game_screen_always_on, yes_or_no_choices[1]);
+            }
+            if (!app->variable_item_game_sound_on)
+            {
+                app->variable_item_game_sound_on = variable_item_list_add(app->variable_item_list, "Sound On?", 2, callback_sound_on_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_sound_on, 0);
+                variable_item_set_current_value_text(app->variable_item_game_sound_on, yes_or_no_choices[0]);
+            }
+            if (!app->variable_item_game_vibration_on)
+            {
+                app->variable_item_game_vibration_on = variable_item_list_add(app->variable_item_list, "Vibration On?", 2, callback_vibration_on_change, NULL);
+                variable_item_set_current_value_index(app->variable_item_game_vibration_on, 0);
+                variable_item_set_current_value_text(app->variable_item_game_vibration_on, yes_or_no_choices[0]);
+            }
+            char _game_player_sprite[8];
+            if (load_char("Game-Player-Sprite", _game_player_sprite, sizeof(_game_player_sprite)))
+            {
+                int index = is_str(_game_player_sprite, "naked") ? 0 : is_str(_game_player_sprite, "sword") ? 1
+                                                                   : is_str(_game_player_sprite, "axe")     ? 2
+                                                                   : is_str(_game_player_sprite, "bow")     ? 3
+                                                                                                            : 0;
+                variable_item_set_current_value_index(app->variable_item_game_player_sprite, index);
+                variable_item_set_current_value_text(
+                    app->variable_item_game_player_sprite,
+                    is_str(player_sprite_choices[index], "naked") ? "None" : player_sprite_choices[index]);
+            }
+            char _game_fps[8];
+            if (load_char("Game-FPS", _game_fps, sizeof(_game_fps)))
+            {
+                int index = is_str(_game_fps, "30") ? 0 : is_str(_game_fps, "60") ? 1
+                                                      : is_str(_game_fps, "120")  ? 2
+                                                      : is_str(_game_fps, "240")  ? 3
+                                                                                  : 0;
+                variable_item_set_current_value_text(app->variable_item_game_fps, fps_choices_str[index]);
+                variable_item_set_current_value_index(app->variable_item_game_fps, index);
+            }
+            char _game_vgm_x[8];
+            if (load_char("Game-VGM-X", _game_vgm_x, sizeof(_game_vgm_x)))
+            {
+                int vgm_x = atoi(_game_vgm_x);
+                int index = vgm_x == -2 ? 0 : vgm_x == -1 ? 1
+                                          : vgm_x == 0    ? 2
+                                          : vgm_x == 1    ? 3
+                                          : vgm_x == 2    ? 4
+                                          : vgm_x == 3    ? 5
+                                          : vgm_x == 4    ? 6
+                                          : vgm_x == 5    ? 7
+                                          : vgm_x == 6    ? 8
+                                          : vgm_x == 7    ? 9
+                                          : vgm_x == 8    ? 10
+                                          : vgm_x == 9    ? 11
+                                          : vgm_x == 10   ? 12
+                                                          : 2;
+                variable_item_set_current_value_index(app->variable_item_game_vgm_x, index);
+                variable_item_set_current_value_text(app->variable_item_game_vgm_x, vgm_levels[index]);
+            }
+            char _game_vgm_y[8];
+            if (load_char("Game-VGM-Y", _game_vgm_y, sizeof(_game_vgm_y)))
+            {
+                int vgm_y = atoi(_game_vgm_y);
+                int index = vgm_y == -2 ? 0 : vgm_y == -1 ? 1
+                                          : vgm_y == 0    ? 2
+                                          : vgm_y == 1    ? 3
+                                          : vgm_y == 2    ? 4
+                                          : vgm_y == 3    ? 5
+                                          : vgm_y == 4    ? 6
+                                          : vgm_y == 5    ? 7
+                                          : vgm_y == 6    ? 8
+                                          : vgm_y == 7    ? 9
+                                          : vgm_y == 8    ? 10
+                                          : vgm_y == 9    ? 11
+                                          : vgm_y == 10   ? 12
+                                                          : 2;
+                variable_item_set_current_value_index(app->variable_item_game_vgm_y, index);
+                variable_item_set_current_value_text(app->variable_item_game_vgm_y, vgm_levels[index]);
+            }
+            char _game_screen_always_on[8];
+            if (load_char("Game-Screen-Always-On", _game_screen_always_on, sizeof(_game_screen_always_on)))
+            {
+                int index = is_str(_game_screen_always_on, "No") ? 0 : is_str(_game_screen_always_on, "Yes") ? 1
+                                                                                                             : 0;
+                variable_item_set_current_value_text(app->variable_item_game_screen_always_on, yes_or_no_choices[index]);
+                variable_item_set_current_value_index(app->variable_item_game_screen_always_on, index);
+            }
+            char _game_sound_on[8];
+            if (load_char("Game-Sound-On", _game_sound_on, sizeof(_game_sound_on)))
+            {
+                int index = is_str(_game_sound_on, "No") ? 0 : is_str(_game_sound_on, "Yes") ? 1
+                                                                                             : 0;
+                variable_item_set_current_value_text(app->variable_item_game_sound_on, yes_or_no_choices[index]);
+                variable_item_set_current_value_index(app->variable_item_game_sound_on, index);
+            }
+            char _game_vibration_on[8];
+            if (load_char("Game-Vibration-On", _game_vibration_on, sizeof(_game_vibration_on)))
+            {
+                int index = is_str(_game_vibration_on, "No") ? 0 : is_str(_game_vibration_on, "Yes") ? 1
+                                                                                                     : 0;
+                variable_item_set_current_value_text(app->variable_item_game_vibration_on, yes_or_no_choices[index]);
+                variable_item_set_current_value_index(app->variable_item_game_vibration_on, index);
+            }
+            break;
+        case FlipWorldSubmenuIndexUserSettings:
+            if (!easy_flipper_set_variable_item_list(&app->variable_item_list, FlipWorldViewVariableItemList, callback_user_settings_select, callback_to_settings, &app->view_dispatcher, app))
+            {
+                FURI_LOG_E(TAG, "Failed to allocate variable item list");
+                return false;
+            }
+
+            if (!app->variable_item_list)
+            {
+                FURI_LOG_E(TAG, "Variable item list is NULL");
+                return false;
+            }
+
+            // if logged in, show profile info, otherwise show login/register
+            if (is_logged_in() || is_logged_in_to_flip_social())
+            {
+                if (!app->variable_item_user_username)
+                {
+                    app->variable_item_user_username = variable_item_list_add(app->variable_item_list, "Username", 0, NULL, NULL);
+                    variable_item_set_current_value_text(app->variable_item_user_username, "");
+                }
+                if (!app->variable_item_user_password)
+                {
+                    app->variable_item_user_password = variable_item_list_add(app->variable_item_list, "Password", 0, NULL, NULL);
+                    variable_item_set_current_value_text(app->variable_item_user_password, "");
+                }
+                if (load_settings(ssid, sizeof(ssid), pass, sizeof(pass), username, sizeof(username), password, sizeof(password)))
+                {
+                    variable_item_set_current_value_text(app->variable_item_user_username, username);
+                    variable_item_set_current_value_text(app->variable_item_user_password, "*****");
+                }
+            }
+            else
+            {
+                if (!app->variable_item_user_username)
+                {
+                    app->variable_item_user_username = variable_item_list_add(app->variable_item_list, "Username", 0, NULL, NULL);
+                    variable_item_set_current_value_text(app->variable_item_user_username, "");
+                }
+                if (!app->variable_item_user_password)
+                {
+                    app->variable_item_user_password = variable_item_list_add(app->variable_item_list, "Password", 0, NULL, NULL);
+                    variable_item_set_current_value_text(app->variable_item_user_password, "");
+                }
+            }
+            break;
+        }
+    }
+    return true;
+}
+bool alloc_submenu_other(void *context, uint32_t view_id)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->submenu_other)
+    {
+        FURI_LOG_I(TAG, "Submenu already allocated");
+        return true;
+    }
+    switch (view_id)
+    {
+    case FlipWorldViewSettings:
+        if (!easy_flipper_set_submenu(&app->submenu_other, FlipWorldViewSubmenuOther, "Settings", callback_to_submenu, &app->view_dispatcher))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate submenu settings");
+            return false;
+        }
+        submenu_add_item(app->submenu_other, "WiFi", FlipWorldSubmenuIndexWiFiSettings, callback_submenu_choices, app);
+        submenu_add_item(app->submenu_other, "Game", FlipWorldSubmenuIndexGameSettings, callback_submenu_choices, app);
+        submenu_add_item(app->submenu_other, "User", FlipWorldSubmenuIndexUserSettings, callback_submenu_choices, app);
+        return true;
+    case FlipWorldViewLobby:
+        return easy_flipper_set_submenu(&app->submenu_other, FlipWorldViewSubmenuOther, "Lobbies", callback_to_submenu, &app->view_dispatcher);
+    default:
+        return false;
+    }
+}
+
+bool alloc_game_submenu(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (!app->submenu_game)
+    {
+        if (!easy_flipper_set_submenu(&app->submenu_game, FlipWorldViewGameSubmenu, "Play", callback_to_submenu, &app->view_dispatcher))
+        {
+            return false;
+        }
+        if (!app->submenu_game)
+        {
+            return false;
+        }
+        submenu_add_item(app->submenu_game, "Story", FlipWorldSubmenuIndexStory, callback_submenu_choices, app);
+        submenu_add_item(app->submenu_game, "PvE", FlipWorldSubmenuIndexPvE, callback_submenu_choices, app);
+        submenu_add_item(app->submenu_game, "PvP", FlipWorldSubmenuIndexPvP, callback_submenu_choices, app);
+    }
+    return true;
+}

+ 9 - 0
flip_world/callback/alloc.h

@@ -0,0 +1,9 @@
+#pragma once
+#include <flip_world.h>
+#include <callback/utils.h>
+
+bool alloc_message_view(void *context, MessageState state);
+bool alloc_text_input_view(void *context, char *title);
+bool alloc_variable_item_list(void *context, uint32_t view_id);
+bool alloc_submenu_other(void *context, uint32_t view_id);
+bool alloc_game_submenu(void *context);

+ 628 - 0
flip_world/callback/callback.c

@@ -0,0 +1,628 @@
+#include <callback/callback.h>
+#include <callback/loader.h>
+#include <callback/free.h>
+#include <callback/alloc.h>
+#include <callback/game.h>
+#include "alloc/alloc.h"
+#include <flip_storage/storage.h>
+
+bool callback_message_input(InputEvent *event, void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (event->key == InputKeyBack)
+    {
+        FURI_LOG_I(TAG, "Message view - BACK pressed");
+        user_hit_back = true;
+    }
+    return true;
+}
+
+void callback_message_draw(Canvas *canvas, void *model)
+{
+    MessageModel *message_model = model;
+    canvas_clear(canvas);
+    if (message_model->message_state == MessageStateAbout)
+    {
+        canvas_draw_str(canvas, 0, 10, VERSION_TAG);
+        canvas_set_font_custom(canvas, FONT_SIZE_SMALL);
+        canvas_draw_str(canvas, 0, 20, "Dev: JBlanked, codeallnight");
+        canvas_draw_str(canvas, 0, 30, "GFX: the1anonlypr3");
+        canvas_draw_str(canvas, 0, 40, "github.com/jblanked/FlipWorld");
+
+        canvas_draw_str_multi(canvas, 0, 55, "The first open world multiplayer\ngame on the Flipper Zero.");
+    }
+    else if (message_model->message_state == MessageStateLoading)
+    {
+        canvas_set_font(canvas, FontPrimary);
+        if (game_mode_index != 1)
+        {
+            canvas_draw_str_aligned(canvas, 64, 0, AlignCenter, AlignTop, "Starting FlipWorld");
+            canvas_set_font(canvas, FontSecondary);
+            canvas_draw_str(canvas, 0, 50, "Please wait while your");
+            canvas_draw_str(canvas, 0, 60, "game is started.");
+        }
+        else
+        {
+            canvas_draw_str_aligned(canvas, 64, 0, AlignCenter, AlignTop, "Loading Lobbies");
+            canvas_set_font(canvas, FontSecondary);
+            canvas_draw_str(canvas, 0, 60, "Please wait....");
+        }
+    }
+    // well this is only called once so let's make a while loop
+    else if (message_model->message_state == MessageStateWaitingLobby)
+    {
+        canvas_draw_str(canvas, 0, 10, "Waiting for more players...");
+        // time elapsed based on timer_iteration and timer_refresh
+        // char str[32];
+        // snprintf(str, sizeof(str), "Time elapsed: %d seconds", timer_iteration * timer_refresh);
+        // canvas_draw_str(canvas, 0, 50, str);
+        canvas_draw_str(canvas, 0, 60, "Press BACK to cancel.");
+        canvas_commit(canvas); // make sure message is drawn
+    }
+    else
+    {
+        canvas_draw_str(canvas, 0, 10, "Unknown message state");
+    }
+}
+
+void callback_submenu_choices(void *context, uint32_t index)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    switch (index)
+    {
+    case FlipWorldSubmenuIndexGameSubmenu:
+        free_all_views(app, true, true, true);
+        if (!alloc_game_submenu(app))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate game submenu");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewGameSubmenu);
+        break;
+    case FlipWorldSubmenuIndexStory:
+        game_mode_index = 2; // GAME_MODE_STORY
+        game_run(app);
+        break;
+    case FlipWorldSubmenuIndexPvP:
+        game_mode_index = 1; // GAME_MODE_PVP
+        game_run(app);
+        break;
+    case FlipWorldSubmenuIndexPvE:
+        game_mode_index = 0; // GAME_MODE_PVE
+        game_run(app);
+        break;
+    case FlipWorldSubmenuIndexMessage:
+        // About menu.
+        free_all_views(app, true, true, true);
+        if (!alloc_message_view(app, MessageStateAbout))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate message view");
+            return;
+        }
+
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewMessage);
+        break;
+    case FlipWorldSubmenuIndexSettings:
+        free_all_views(app, true, true, true);
+        if (!alloc_submenu_other(app, FlipWorldViewSettings))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate settings view");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+        break;
+    case FlipWorldSubmenuIndexWiFiSettings:
+        free_all_views(app, true, false, true);
+        if (!alloc_variable_item_list(app, FlipWorldSubmenuIndexWiFiSettings))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate variable item list");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+        break;
+    case FlipWorldSubmenuIndexGameSettings:
+        free_all_views(app, true, false, true);
+        if (!alloc_variable_item_list(app, FlipWorldSubmenuIndexGameSettings))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate variable item list");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+        break;
+    case FlipWorldSubmenuIndexUserSettings:
+        free_all_views(app, true, false, true);
+        if (!alloc_variable_item_list(app, FlipWorldSubmenuIndexUserSettings))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate variable item list");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+        break;
+    default:
+        break;
+    }
+}
+
+void callback_updated_wifi_ssid(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+
+    // store the entered text
+    strncpy(app->text_input_buffer, app->text_input_temp_buffer, app->text_input_buffer_size);
+
+    // Ensure null-termination
+    app->text_input_buffer[app->text_input_buffer_size - 1] = '\0';
+
+    // save the setting
+    save_char("WiFi-SSID", app->text_input_buffer);
+
+    // update the variable item text
+    if (app->variable_item_wifi_ssid)
+    {
+        variable_item_set_current_value_text(app->variable_item_wifi_ssid, app->text_input_buffer);
+
+        // get value of password
+        char pass[64];
+        char username[64];
+        char password[64];
+        if (load_char("WiFi-Password", pass, sizeof(pass)))
+        {
+            if (strlen(pass) > 0 && strlen(app->text_input_buffer) > 0)
+            {
+                // save the settings
+                load_char("Flip-Social-Username", username, sizeof(username));
+                load_char("Flip-Social-Password", password, sizeof(password));
+                save_settings(app->text_input_buffer, pass, username, password);
+
+                // initialize the http
+                FlipperHTTP *fhttp = flipper_http_alloc();
+                if (fhttp)
+                {
+                    // save the wifi if the device is connected
+                    if (!flipper_http_save_wifi(fhttp, app->text_input_buffer, pass))
+                    {
+                        easy_flipper_dialog("FlipperHTTP Error", "Ensure your WiFi Developer\nBoard or Pico W is connected\nand the latest FlipperHTTP\nfirmware is installed.");
+                    }
+
+                    // free the resources
+                    flipper_http_free(fhttp);
+                }
+                else
+                {
+                    easy_flipper_dialog("FlipperHTTP Error", "The UART is likely busy.\nEnsure you have the correct\nflash for your board then\nrestart your Flipper Zero.");
+                }
+            }
+        }
+    }
+
+    // switch to the settings view
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+}
+void callback_updated_wifi_pass(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+
+    // store the entered text
+    strncpy(app->text_input_buffer, app->text_input_temp_buffer, app->text_input_buffer_size);
+
+    // Ensure null-termination
+    app->text_input_buffer[app->text_input_buffer_size - 1] = '\0';
+
+    // save the setting
+    save_char("WiFi-Password", app->text_input_buffer);
+
+    // update the variable item text
+    if (app->variable_item_wifi_pass)
+    {
+        // variable_item_set_current_value_text(app->variable_item_wifi_pass, app->text_input_buffer);
+    }
+
+    // get value of ssid
+    char ssid[64];
+    char username[64];
+    char password[64];
+    if (load_char("WiFi-SSID", ssid, sizeof(ssid)))
+    {
+        if (strlen(ssid) > 0 && strlen(app->text_input_buffer) > 0)
+        {
+            // save the settings
+            load_char("Flip-Social-Username", username, sizeof(username));
+            load_char("Flip-Social-Password", password, sizeof(password));
+            save_settings(ssid, app->text_input_buffer, username, password);
+
+            // initialize the http
+            FlipperHTTP *fhttp = flipper_http_alloc();
+            if (fhttp)
+            {
+                // save the wifi if the device is connected
+                if (!flipper_http_save_wifi(fhttp, ssid, app->text_input_buffer))
+                {
+                    easy_flipper_dialog("FlipperHTTP Error", "Ensure your WiFi Developer\nBoard or Pico W is connected\nand the latest FlipperHTTP\nfirmware is installed.");
+                }
+
+                // free the resources
+                flipper_http_free(fhttp);
+            }
+            else
+            {
+                easy_flipper_dialog("FlipperHTTP Error", "The UART is likely busy.\nEnsure you have the correct\nflash for your board then\nrestart your Flipper Zero.");
+            }
+        }
+    }
+
+    // switch to the settings view
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+}
+void callback_updated_username(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+
+    // store the entered text
+    strncpy(app->text_input_buffer, app->text_input_temp_buffer, app->text_input_buffer_size);
+
+    // Ensure null-termination
+    app->text_input_buffer[app->text_input_buffer_size - 1] = '\0';
+
+    // save the setting
+    save_char("Flip-Social-Username", app->text_input_buffer);
+
+    // update the variable item text
+    if (app->variable_item_user_username)
+    {
+        variable_item_set_current_value_text(app->variable_item_user_username, app->text_input_buffer);
+    }
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList); // back to user settings
+}
+void callback_updated_password(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+
+    // store the entered text
+    strncpy(app->text_input_buffer, app->text_input_temp_buffer, app->text_input_buffer_size);
+
+    // Ensure null-termination
+    app->text_input_buffer[app->text_input_buffer_size - 1] = '\0';
+
+    // save the setting
+    save_char("Flip-Social-Password", app->text_input_buffer);
+
+    // update the variable item text
+    if (app->variable_item_user_password)
+    {
+        variable_item_set_current_value_text(app->variable_item_user_password, app->text_input_buffer);
+    }
+
+    // get value of username
+    char username[64];
+    char ssid[64];
+    char pass[64];
+    if (load_char("Flip-Social-Username", username, sizeof(username)))
+    {
+        if (strlen(username) > 0 && strlen(app->text_input_buffer) > 0)
+        {
+            // save the settings
+            load_char("WiFi-SSID", ssid, sizeof(ssid));
+            load_char("WiFi-Password", pass, sizeof(pass));
+            save_settings(ssid, pass, username, app->text_input_buffer);
+        }
+    }
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewVariableItemList); // back to user settings
+}
+
+void callback_wifi_settings_select(void *context, uint32_t index)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    char ssid[64];
+    char pass[64];
+    char username[64];
+    char password[64];
+    switch (index)
+    {
+    case 0: // Input SSID
+        free_all_views(app, false, false, true);
+        if (!alloc_text_input_view(app, "SSID"))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate text input view");
+            return;
+        }
+        // load SSID
+        if (load_settings(ssid, sizeof(ssid), pass, sizeof(pass), username, sizeof(username), password, sizeof(password)))
+        {
+            strncpy(app->text_input_temp_buffer, ssid, app->text_input_buffer_size - 1);
+            app->text_input_temp_buffer[app->text_input_buffer_size - 1] = '\0';
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewTextInput);
+        break;
+    case 1: // Input Password
+        free_all_views(app, false, false, true);
+        if (!alloc_text_input_view(app, "Password"))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate text input view");
+            return;
+        }
+        // load password
+        if (load_settings(ssid, sizeof(ssid), pass, sizeof(pass), username, sizeof(username), password, sizeof(password)))
+        {
+            strncpy(app->text_input_temp_buffer, pass, app->text_input_buffer_size - 1);
+            app->text_input_temp_buffer[app->text_input_buffer_size - 1] = '\0';
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewTextInput);
+        break;
+    default:
+        FURI_LOG_E(TAG, "Unknown configuration item index");
+        break;
+    }
+}
+void callback_fps_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    fps_index = index;
+    variable_item_set_current_value_text(item, fps_choices_str[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-FPS", fps_choices_str[index]);
+}
+void callback_screen_on_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    screen_always_on_index = index;
+    variable_item_set_current_value_text(item, yes_or_no_choices[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-Screen-Always-On", yes_or_no_choices[index]);
+}
+void callback_sound_on_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    sound_on_index = index;
+    variable_item_set_current_value_text(item, yes_or_no_choices[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-Sound-On", yes_or_no_choices[index]);
+}
+void callback_vibration_on_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    vibration_on_index = index;
+    variable_item_set_current_value_text(item, yes_or_no_choices[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-Vibration-On", yes_or_no_choices[index]);
+}
+void callback_player_on_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    player_sprite_index = index;
+    variable_item_set_current_value_text(item, is_str(player_sprite_choices[index], "naked") ? "None" : player_sprite_choices[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-Player-Sprite", player_sprite_choices[index]);
+}
+void callback_vgm_x_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    vgm_x_index = index;
+    variable_item_set_current_value_text(item, vgm_levels[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-VGM-X", vgm_levels[index]);
+}
+void callback_vgm_y_change(VariableItem *item)
+{
+    uint8_t index = variable_item_get_current_value_index(item);
+    vgm_y_index = index;
+    variable_item_set_current_value_text(item, vgm_levels[index]);
+    variable_item_set_current_value_index(item, index);
+    save_char("Game-VGM-Y", vgm_levels[index]);
+}
+
+static bool _fetch_worlds(DataLoaderModel *model)
+{
+    if (!model || !model->fhttp)
+    {
+        FURI_LOG_E(TAG, "model or fhttp is NULL");
+        return false;
+    }
+    char directory_path[128];
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world");
+    Storage *storage = furi_record_open(RECORD_STORAGE);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds");
+    storage_common_mkdir(storage, directory_path);
+    furi_record_close(RECORD_STORAGE);
+    snprintf(model->fhttp->file_path, sizeof(model->fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/world_list_full.json");
+    model->fhttp->save_received_data = true;
+    return flipper_http_request(model->fhttp, GET, "https://www.jblanked.com/flipper/api/world/v8/get/10/", "{\"Content-Type\":\"application/json\"}", NULL);
+}
+static char *_parse_worlds(DataLoaderModel *model)
+{
+    UNUSED(model);
+    return "World Pack Installed";
+}
+static void switch_to_view_get_worlds(FlipWorldApp *app)
+{
+    if (!loader_view_alloc(app))
+    {
+        FURI_LOG_E(TAG, "Failed to allocate view loader");
+        return;
+    }
+    loader_switch_to_view(app, "Fetching World Pack..", _fetch_worlds, _parse_worlds, 1, callback_to_submenu, FlipWorldViewLoader);
+}
+void callback_game_settings_select(void *context, uint32_t index)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    switch (index)
+    {
+    case 0: // Download all world data as one huge json
+        switch_to_view_get_worlds(app);
+    case 1: // Player Sprite
+        break;
+    case 2: // Change FPS
+        break;
+    case 3: // VGM X
+        break;
+    case 4: // VGM Y
+        break;
+    case 5: // Screen Always On
+        break;
+    case 6: // Sound On
+        break;
+    case 7: // Vibration On
+        break;
+    }
+}
+void callback_user_settings_select(void *context, uint32_t index)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    switch (index)
+    {
+    case 0: // Username
+        free_all_views(app, false, false, true);
+        if (!alloc_text_input_view(app, "Username-Login"))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate text input view");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewTextInput);
+        break;
+    case 1: // Password
+        free_all_views(app, false, false, true);
+        if (!alloc_text_input_view(app, "Password-Login"))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate text input view");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewTextInput);
+        break;
+    }
+}
+
+void callback_submenu_lobby_pvp_choices(void *context, uint32_t index)
+{
+    /* Handle other game lobbies
+             1. when clicked on, send request to fetch the selected game lobby details
+             2. start the websocket session
+             3. start the game thread (the rest will be handled by game_start_game and player_update)
+             */
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    if (index >= FlipWorldSubmenuIndexLobby && index < FlipWorldSubmenuIndexLobby + 10)
+    {
+        lobby_index = index - FlipWorldSubmenuIndexLobby;
+
+        FlipperHTTP *fhttp = flipper_http_alloc();
+        if (!fhttp)
+        {
+            FURI_LOG_E(TAG, "Failed to allocate FlipperHTTP");
+            easy_flipper_dialog("Error", "Failed to allocate FlipperHTTP. Press BACK to return.");
+            return;
+        }
+
+        // fetch the lobby details
+        if (!game_fetch_lobby(fhttp, lobby_list[lobby_index]))
+        {
+            FURI_LOG_E(TAG, "Failed to fetch lobby details");
+            easy_flipper_dialog("Error", "Failed to fetch lobby details. Press BACK to return.");
+            flipper_http_free(fhttp);
+            return;
+        }
+
+        // load the lobby details
+        FuriString *lobby = flipper_http_load_from_file(fhttp->file_path);
+        if (!lobby)
+        {
+            FURI_LOG_E(TAG, "Failed to load lobby details");
+            flipper_http_free(fhttp);
+            return;
+        }
+
+        // if there are no players, add the user to the lobby and make the user wait until another player joins
+        // if there is one player and it's the user, make the user wait until another player joins
+        // if there is one player and it's not the user, parse_lobby and start websocket
+        // if there are 2 players (which there shouldn't be at this point), show an error message saying the lobby is full
+        if (game_mode_index == 1) // pvp
+        {
+            switch (game_lobby_count(fhttp, lobby))
+            {
+            case -1:
+                FURI_LOG_E(TAG, "Failed to get player count");
+                easy_flipper_dialog("Error", "Failed to get player count. Press BACK to return.");
+                flipper_http_free(fhttp);
+                furi_string_free(lobby);
+                return;
+            case 0:
+                // add the user to the lobby
+                if (!game_join_lobby(fhttp, lobby_list[lobby_index]))
+                {
+                    FURI_LOG_E(TAG, "Failed to join lobby");
+                    easy_flipper_dialog("Error", "Failed to join lobby. Press BACK to return.");
+                    flipper_http_free(fhttp);
+                    furi_string_free(lobby);
+                    return;
+                }
+                // send the user to the waiting screen
+                game_waiting_lobby(app);
+                return;
+            case 1:
+                // check if the user is in the lobby
+                if (game_in_lobby(fhttp, lobby))
+                {
+                    if (!game_remove_from_lobby(fhttp))
+                    {
+                        FURI_LOG_I(TAG, "User is in the lobby but failed to remove");
+                        easy_flipper_dialog("Error", "You're already in the lobby.\nContact JBlanked.\n\nPress BACK to return.");
+                        flipper_http_free(fhttp);
+                        furi_string_free(lobby);
+                        return;
+                    }
+                }
+                // add the user to the lobby
+                if (!game_join_lobby(fhttp, lobby_list[lobby_index]))
+                {
+                    FURI_LOG_E(TAG, "Failed to join lobby");
+                    easy_flipper_dialog("Error", "Failed to join lobby. Press BACK to return.");
+                    flipper_http_free(fhttp);
+                    furi_string_free(lobby);
+                    return;
+                }
+                break;
+            case 2:
+                // show an error message saying the lobby is full
+                FURI_LOG_E(TAG, "Lobby is full");
+                easy_flipper_dialog("Error", "Lobby is full. Press BACK to return.");
+                flipper_http_free(fhttp);
+                furi_string_free(lobby);
+                return;
+            };
+        }
+        else
+        {
+            // check if the user is in the lobby
+            if (game_in_lobby(fhttp, lobby))
+            {
+                if (!game_remove_from_lobby(fhttp))
+                {
+                    FURI_LOG_I(TAG, "User is in the lobby but failed to remove");
+                    easy_flipper_dialog("Error", "You're already in the lobby.\nContact JBlanked.\n\nPress BACK to return.");
+                    flipper_http_free(fhttp);
+                    furi_string_free(lobby);
+                    return;
+                }
+            }
+            // add the user to the lobby
+            if (!game_join_lobby(fhttp, lobby_list[lobby_index]))
+            {
+                FURI_LOG_E(TAG, "Failed to join lobby");
+                easy_flipper_dialog("Error", "Failed to join lobby. Press BACK to return.");
+                flipper_http_free(fhttp);
+                furi_string_free(lobby);
+                return;
+            }
+        }
+
+        game_start_game(fhttp, lobby, app); // this will free both the fhttp and lobby, and start the game
+    }
+}

+ 21 - 0
flip_world/callback/callback.h

@@ -0,0 +1,21 @@
+#pragma once
+#include <flip_world.h>
+
+void callback_submenu_choices(void *context, uint32_t index);
+bool callback_message_input(InputEvent *event, void *context);
+void callback_message_draw(Canvas *canvas, void *model);
+void callback_wifi_settings_select(void *context, uint32_t index);
+void callback_updated_wifi_ssid(void *context);
+void callback_updated_wifi_pass(void *context);
+void callback_updated_username(void *context);
+void callback_updated_password(void *context);
+void callback_fps_change(VariableItem *item);
+void callback_game_settings_select(void *context, uint32_t index);
+void callback_user_settings_select(void *context, uint32_t index);
+void callback_screen_on_change(VariableItem *item);
+void callback_sound_on_change(VariableItem *item);
+void callback_vibration_on_change(VariableItem *item);
+void callback_player_on_change(VariableItem *item);
+void callback_vgm_x_change(VariableItem *item);
+void callback_vgm_y_change(VariableItem *item);
+void callback_submenu_lobby_pvp_choices(void *context, uint32_t index);

+ 192 - 0
flip_world/callback/free.c

@@ -0,0 +1,192 @@
+#include "callback/free.h"
+#include "callback/loader.h"
+#include "callback/game.h"
+
+void free_game_submenu(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->submenu_game)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewGameSubmenu);
+        submenu_free(app->submenu_game);
+        app->submenu_game = NULL;
+    }
+}
+
+void free_submenu_other(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->submenu_other)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+        submenu_free(app->submenu_other);
+        app->submenu_other = NULL;
+    }
+    for (int i = 0; i < 10; i++)
+    {
+        if (lobby_list[i])
+        {
+            free(lobby_list[i]);
+            lobby_list[i] = NULL;
+        }
+    }
+}
+
+void free_message_view(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->view_message)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewMessage);
+        view_free(app->view_message);
+        app->view_message = NULL;
+    }
+}
+
+void free_text_input_view(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->text_input)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewTextInput);
+        uart_text_input_free(app->text_input);
+        app->text_input = NULL;
+    }
+    if (app->text_input_buffer)
+    {
+        free(app->text_input_buffer);
+        app->text_input_buffer = NULL;
+    }
+    if (app->text_input_temp_buffer)
+    {
+        free(app->text_input_temp_buffer);
+        app->text_input_temp_buffer = NULL;
+    }
+}
+
+void free_variable_item_list(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (app->variable_item_list)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewVariableItemList);
+        variable_item_list_free(app->variable_item_list);
+        app->variable_item_list = NULL;
+    }
+    if (app->variable_item_wifi_ssid)
+    {
+        free(app->variable_item_wifi_ssid);
+        app->variable_item_wifi_ssid = NULL;
+    }
+    if (app->variable_item_wifi_pass)
+    {
+        free(app->variable_item_wifi_pass);
+        app->variable_item_wifi_pass = NULL;
+    }
+    if (app->variable_item_game_fps)
+    {
+        free(app->variable_item_game_fps);
+        app->variable_item_game_fps = NULL;
+    }
+    if (app->variable_item_game_screen_always_on)
+    {
+        free(app->variable_item_game_screen_always_on);
+        app->variable_item_game_screen_always_on = NULL;
+    }
+    if (app->variable_item_game_download_world)
+    {
+        free(app->variable_item_game_download_world);
+        app->variable_item_game_download_world = NULL;
+    }
+    if (app->variable_item_game_sound_on)
+    {
+        free(app->variable_item_game_sound_on);
+        app->variable_item_game_sound_on = NULL;
+    }
+    if (app->variable_item_game_vibration_on)
+    {
+        free(app->variable_item_game_vibration_on);
+        app->variable_item_game_vibration_on = NULL;
+    }
+    if (app->variable_item_game_player_sprite)
+    {
+        free(app->variable_item_game_player_sprite);
+        app->variable_item_game_player_sprite = NULL;
+    }
+    if (app->variable_item_game_vgm_x)
+    {
+        free(app->variable_item_game_vgm_x);
+        app->variable_item_game_vgm_x = NULL;
+    }
+    if (app->variable_item_game_vgm_y)
+    {
+        free(app->variable_item_game_vgm_y);
+        app->variable_item_game_vgm_y = NULL;
+    }
+    if (app->variable_item_user_username)
+    {
+        free(app->variable_item_user_username);
+        app->variable_item_user_username = NULL;
+    }
+    if (app->variable_item_user_password)
+    {
+        free(app->variable_item_user_password);
+        app->variable_item_user_password = NULL;
+    }
+}
+
+void free_all_views(void *context, bool free_variable_list, bool free_settings_other, bool free_submenu_game)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    if (free_variable_list)
+    {
+        free_variable_item_list(app);
+    }
+    free_message_view(app);
+    free_text_input_view(app);
+
+    // free game thread
+    if (game_thread_running)
+    {
+        game_thread_running = false;
+        if (game_thread)
+        {
+            furi_thread_flags_set(furi_thread_get_id(game_thread), WorkerEvtStop);
+            furi_thread_join(game_thread);
+            furi_thread_free(game_thread);
+            game_thread = NULL;
+        }
+    }
+
+    if (free_settings_other)
+    {
+        free_submenu_other(app);
+    }
+
+    // free Derek's loader
+    loader_view_free(app);
+
+    if (free_submenu_game)
+    {
+        free_game_submenu(app);
+    }
+
+    // free waiting thread
+    if (waiting_thread_running)
+    {
+        waiting_thread_running = false;
+        if (waiting_thread)
+        {
+            furi_thread_flags_set(furi_thread_get_id(waiting_thread), WorkerEvtStop);
+            furi_thread_join(waiting_thread);
+            furi_thread_free(waiting_thread);
+            waiting_thread = NULL;
+        }
+    }
+}

+ 9 - 0
flip_world/callback/free.h

@@ -0,0 +1,9 @@
+#pragma once
+#include <flip_world.h>
+
+void free_game_submenu(void *context);
+void free_submenu_other(void *context);
+void free_message_view(void *context);
+void free_text_input_view(void *context);
+void free_variable_item_list(void *context);
+void free_all_views(void *context, bool free_variable_list, bool free_settings_other, bool free_submenu_game);

+ 1174 - 0
flip_world/callback/game.c

@@ -0,0 +1,1174 @@
+#include <callback/game.h>
+//
+#include "engine/engine.h"
+#include "engine/game_engine.h"
+#include "engine/game_manager_i.h"
+#include "engine/level_i.h"
+#include "engine/entity_i.h"
+//
+#include "game/storage.h"
+//
+#include <callback/loader.h>
+#include <callback/free.h>
+#include <callback/alloc.h>
+#include <callback/callback.h>
+#include "alloc/alloc.h"
+#include <flip_storage/storage.h>
+
+bool user_hit_back = false;
+uint32_t lobby_index = -1;
+char *lobby_list[10];
+char game_ws_lobby_name[64];
+
+static uint8_t timer_iteration = 0; // timer iteration for the loading screen
+static uint8_t timer_refresh = 5;   // duration for timer to refresh
+
+FuriThread *game_thread = NULL;
+FuriThread *waiting_thread = NULL;
+bool game_thread_running = false;
+bool waiting_thread_running = false;
+
+static void game_frame_cb(GameEngine *engine, Canvas *canvas, InputState input, void *context)
+{
+    UNUSED(engine);
+    GameManager *game_manager = context;
+    game_manager_input_set(game_manager, input);
+    game_manager_update(game_manager);
+    game_manager_render(game_manager, canvas);
+}
+
+static int32_t game_app(void *p)
+{
+    UNUSED(p);
+    GameManager *game_manager = game_manager_alloc();
+    if (!game_manager)
+    {
+        FURI_LOG_E("Game", "Failed to allocate game manager");
+        return -1;
+    }
+
+    // Setup game engine settings...
+    GameEngineSettings settings = game_engine_settings_init();
+    settings.target_fps = atof_(fps_choices_str[fps_index]);
+    settings.show_fps = game.show_fps;
+    settings.always_backlight = strstr(yes_or_no_choices[screen_always_on_index], "Yes") != NULL;
+    settings.frame_callback = game_frame_cb;
+    settings.context = game_manager;
+    GameEngine *engine = game_engine_alloc(settings);
+    if (!engine)
+    {
+        FURI_LOG_E("Game", "Failed to allocate game engine");
+        game_manager_free(game_manager);
+        return -1;
+    }
+    game_manager_engine_set(game_manager, engine);
+
+    // Allocate custom game context if needed
+    void *game_context = NULL;
+    if (game.context_size > 0)
+    {
+        game_context = malloc(game.context_size);
+        game_manager_game_context_set(game_manager, game_context);
+    }
+
+    // Start the game
+    game.start(game_manager, game_context);
+
+    // 1) Run the engine
+    game_engine_run(engine);
+
+    // 2) Stop the game FIRST, so it can do any internal cleanup
+    game.stop(game_context);
+
+    // 3) Now free the engine
+    game_engine_free(engine);
+
+    // 4) Now free the manager
+    game_manager_free(game_manager);
+
+    // 5) Finally, free your custom context if it was allocated
+    if (game_context)
+    {
+        free(game_context);
+    }
+
+    // 6) Check for leftover entities
+    int32_t entities = entities_get_count();
+    if (entities != 0)
+    {
+        FURI_LOG_E("Game", "Memory leak detected: %ld entities still allocated", entities);
+        return -1;
+    }
+
+    return 0;
+}
+
+static int32_t game_waiting_app_callback(void *p)
+{
+    FlipWorldApp *app = (FlipWorldApp *)p;
+    furi_check(app);
+    FlipperHTTP *fhttp = flipper_http_alloc();
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "Failed to allocate FlipperHTTP");
+        easy_flipper_dialog("Error", "Failed to allocate FlipperHTTP");
+        return -1;
+    }
+    user_hit_back = false;
+    timer_iteration = 0;
+    while (timer_iteration < 60 && !user_hit_back)
+    {
+        FURI_LOG_I(TAG, "Waiting for more players...");
+        game_waiting_process(fhttp, app);
+        FURI_LOG_I(TAG, "Waiting for more players... %d", timer_iteration);
+        timer_iteration++;
+        furi_delay_ms(1000 * timer_refresh);
+    }
+    // if we reach here, it means we timed out or the user hit back
+    FURI_LOG_E(TAG, "No players joined within the timeout or user hit back");
+    game_remove_from_lobby(fhttp);
+    flipper_http_free(fhttp);
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+    return 0;
+}
+
+static bool game_start_waiting_thread(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    // free game thread
+    if (waiting_thread_running)
+    {
+        waiting_thread_running = false;
+        if (waiting_thread)
+        {
+            furi_thread_flags_set(furi_thread_get_id(waiting_thread), WorkerEvtStop);
+            furi_thread_join(waiting_thread);
+            furi_thread_free(waiting_thread);
+        }
+    }
+    // start waiting thread
+    FuriThread *thread = furi_thread_alloc_ex("waiting_thread", 2048, game_waiting_app_callback, app);
+    if (!thread)
+    {
+        FURI_LOG_E(TAG, "Failed to allocate waiting thread");
+        easy_flipper_dialog("Error", "Failed to allocate waiting thread. Restart your Flipper.");
+        return false;
+    }
+    furi_thread_start(thread);
+    waiting_thread = thread;
+    waiting_thread_running = true;
+    return true;
+}
+
+static bool game_fetch_world_list(FlipperHTTP *fhttp)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "fhttp is NULL");
+        easy_flipper_dialog("Error", "fhttp is NULL. Press BACK to return.");
+        return false;
+    }
+
+    // ensure flip_world directory exists
+    char directory_path[128];
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world");
+    Storage *storage = furi_record_open(RECORD_STORAGE);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds");
+    storage_common_mkdir(storage, directory_path);
+    furi_record_close(RECORD_STORAGE);
+
+    snprintf(fhttp->file_path, sizeof(fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/world_list.json");
+
+    fhttp->save_received_data = true;
+    return flipper_http_request(fhttp, GET, "https://www.jblanked.com/flipper/api/world/v8/list/10/", "{\"Content-Type\":\"application/json\"}", NULL);
+}
+// we will load the palyer stats from the API and save them
+// in player_spawn game method, it will load the player stats that we saved
+static bool game_fetch_player_stats(FlipperHTTP *fhttp)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "fhttp is NULL");
+        easy_flipper_dialog("Error", "fhttp is NULL. Press BACK to return.");
+        return false;
+    }
+    char username[64];
+    if (!load_char("Flip-Social-Username", username, sizeof(username)))
+    {
+        FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+        easy_flipper_dialog("Error", "Failed to load saved username. Go to settings to update.");
+        return false;
+    }
+    char url[128];
+    snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/user/game-stats/%s/", username);
+
+    // ensure the folders exist
+    char directory_path[128];
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world");
+    Storage *storage = furi_record_open(RECORD_STORAGE);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/data");
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/data/player");
+    storage_common_mkdir(storage, directory_path);
+    furi_record_close(RECORD_STORAGE);
+
+    snprintf(fhttp->file_path, sizeof(fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/data/player/player_stats.json");
+    fhttp->save_received_data = true;
+    return flipper_http_request(fhttp, GET, url, "{\"Content-Type\":\"application/json\"}", NULL);
+}
+
+static bool game_thread_start(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    if (!app)
+    {
+        FURI_LOG_E(TAG, "app is NULL");
+        easy_flipper_dialog("Error", "app is NULL. Press BACK to return.");
+        return false;
+    }
+
+    // free everything but message_view
+    free_variable_item_list(app);
+    free_text_input_view(app);
+    // free_submenu_other(app); // free lobby list or settings
+    loader_view_free(app);
+    free_game_submenu(app);
+
+    // free game thread
+    if (game_thread_running)
+    {
+        game_thread_running = false;
+        if (game_thread)
+        {
+            furi_thread_flags_set(furi_thread_get_id(game_thread), WorkerEvtStop);
+            furi_thread_join(game_thread);
+            furi_thread_free(game_thread);
+        }
+    }
+    // start game thread
+    FuriThread *thread = furi_thread_alloc_ex("game", 2048, game_app, app);
+    if (!thread)
+    {
+        FURI_LOG_E(TAG, "Failed to allocate game thread");
+        easy_flipper_dialog("Error", "Failed to allocate game thread. Restart your Flipper.");
+        return false;
+    }
+    furi_thread_start(thread);
+    game_thread = thread;
+    game_thread_running = true;
+    return true;
+}
+// combine register, login, and world list fetch into one function to switch to the loader view
+static bool game_fetch(DataLoaderModel *model)
+{
+    FlipWorldApp *app = (FlipWorldApp *)model->parser_context;
+    if (!app)
+    {
+        FURI_LOG_E(TAG, "app is NULL");
+        easy_flipper_dialog("Error", "app is NULL. Press BACK to return.");
+        return false;
+    }
+    if (model->request_index == 0)
+    {
+        // login
+        char username[64];
+        char password[64];
+        if (!load_char("Flip-Social-Username", username, sizeof(username)))
+        {
+            FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            easy_flipper_dialog("Error", "Failed to load saved username\nGo to user settings to update.");
+            return false;
+        }
+        if (!load_char("Flip-Social-Password", password, sizeof(password)))
+        {
+            FURI_LOG_E(TAG, "Failed to load Flip-Social-Password");
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            easy_flipper_dialog("Error", "Failed to load saved password\nGo to settings to update.");
+            return false;
+        }
+        char payload[256];
+        snprintf(payload, sizeof(payload), "{\"username\":\"%s\",\"password\":\"%s\"}", username, password);
+        return flipper_http_request(model->fhttp, POST, "https://www.jblanked.com/flipper/api/user/login/", "{\"Content-Type\":\"application/json\"}", payload);
+    }
+    else if (model->request_index == 1)
+    {
+        // check if login was successful
+        char is_logged_in[8];
+        if (!load_char("is_logged_in", is_logged_in, sizeof(is_logged_in)))
+        {
+            FURI_LOG_E(TAG, "Failed to load is_logged_in");
+            easy_flipper_dialog("Error", "Failed to load is_logged_in\nGo to user settings to update.");
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            return false;
+        }
+        if (is_str(is_logged_in, "false") && is_str(model->title, "Registering..."))
+        {
+            // register
+            char username[64];
+            char password[64];
+            if (!load_char("Flip-Social-Username", username, sizeof(username)))
+            {
+                FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+                easy_flipper_dialog("Error", "Failed to load saved username. Go to settings to update.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return false;
+            }
+            if (!load_char("Flip-Social-Password", password, sizeof(password)))
+            {
+                FURI_LOG_E(TAG, "Failed to load Flip-Social-Password");
+                easy_flipper_dialog("Error", "Failed to load saved password. Go to settings to update.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return false;
+            }
+            char payload[172];
+            snprintf(payload, sizeof(payload), "{\"username\":\"%s\",\"password\":\"%s\"}", username, password);
+            model->title = "Registering...";
+            return flipper_http_request(model->fhttp, POST, "https://www.jblanked.com/flipper/api/user/register/", "{\"Content-Type\":\"application/json\"}", payload);
+        }
+        else
+        {
+            model->title = "Fetching World List..";
+            return game_fetch_world_list(model->fhttp);
+        }
+    }
+    else if (model->request_index == 2)
+    {
+        model->title = "Fetching World List..";
+        return game_fetch_world_list(model->fhttp);
+    }
+    else if (model->request_index == 3)
+    {
+        snprintf(model->fhttp->file_path, sizeof(model->fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/world_list.json");
+
+        FuriString *world_list = flipper_http_load_from_file(model->fhttp->file_path);
+        if (!world_list)
+        {
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            FURI_LOG_E(TAG, "Failed to load world list");
+            easy_flipper_dialog("Error", "Failed to load world list. Go to game settings to download packs.");
+            return false;
+        }
+        FuriString *first_world = get_json_array_value_furi("worlds", 0, world_list);
+        if (!first_world)
+        {
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            FURI_LOG_E(TAG, "Failed to get first world");
+            easy_flipper_dialog("Error", "Failed to get first world. Go to game settings to download packs.");
+            furi_string_free(world_list);
+            return false;
+        }
+        if (world_exists(furi_string_get_cstr(first_world)))
+        {
+            furi_string_free(world_list);
+            furi_string_free(first_world);
+
+            if (!game_thread_start(app))
+            {
+                FURI_LOG_E(TAG, "Failed to start game thread");
+                easy_flipper_dialog("Error", "Failed to start game thread. Press BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return "Failed to start game thread";
+            }
+            return true;
+        }
+        snprintf(model->fhttp->file_path, sizeof(model->fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/%s.json", furi_string_get_cstr(first_world));
+
+        model->fhttp->save_received_data = true;
+        char url[128];
+        snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/world/v8/get/world/%s/", furi_string_get_cstr(first_world));
+        furi_string_free(world_list);
+        furi_string_free(first_world);
+        return flipper_http_request(model->fhttp, GET, url, "{\"Content-Type\":\"application/json\"}", NULL);
+    }
+    FURI_LOG_E(TAG, "Unknown request index");
+    return false;
+}
+static char *game_parse(DataLoaderModel *model)
+{
+    FlipWorldApp *app = (FlipWorldApp *)model->parser_context;
+
+    if (model->request_index == 0)
+    {
+        if (!model->fhttp->last_response)
+        {
+            save_char("is_logged_in", "false");
+            // Go back to the main menu
+            easy_flipper_dialog("Error", "Response is empty. Press BACK to return.");
+            view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+            return "Response is empty...";
+        }
+
+        // Check for successful conditions
+        if (strstr(model->fhttp->last_response, "[SUCCESS]") != NULL || strstr(model->fhttp->last_response, "User found") != NULL)
+        {
+            save_char("is_logged_in", "true");
+            model->title = "Login successful!";
+            model->title = "Fetching World List..";
+            return "Login successful!";
+        }
+
+        // Check if user not found
+        if (strstr(model->fhttp->last_response, "User not found") != NULL)
+        {
+            save_char("is_logged_in", "false");
+            model->title = "Registering...";
+            return "Account not found...\nRegistering now.."; // if they see this an issue happened switching to register
+        }
+
+        // If not success, not found, check length conditions
+        size_t resp_len = strlen(model->fhttp->last_response);
+        if (resp_len == 0 || resp_len > 127)
+        {
+            // Empty or too long means failed login
+            save_char("is_logged_in", "false");
+            // Go back to the main menu
+            easy_flipper_dialog("Error", "Failed to login. Press BACK to return.");
+            view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+            return "Failed to login...";
+        }
+
+        // Handle any other unknown response as a failure
+        save_char("is_logged_in", "false");
+        // Go back to the main menu
+        easy_flipper_dialog("Error", "Failed to login. Press BACK to return.");
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+        return "Failed to login...";
+    }
+    else if (model->request_index == 1)
+    {
+        if (is_str(model->title, "Registering..."))
+        {
+            // check registration response
+            if (model->fhttp->last_response != NULL && (strstr(model->fhttp->last_response, "[SUCCESS]") != NULL || strstr(model->fhttp->last_response, "User created") != NULL))
+            {
+                save_char("is_logged_in", "true");
+                char username[64];
+                char password[64];
+                // load the username and password, then save them
+                if (!load_char("Flip-Social-Username", username, sizeof(username)))
+                {
+                    FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+                    easy_flipper_dialog("Error", "Failed to load Flip-Social-Username");
+                    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+                    return "Failed to load Flip-Social-Username";
+                }
+                if (!load_char("Flip-Social-Password", password, sizeof(password)))
+                {
+                    FURI_LOG_E(TAG, "Failed to load Flip-Social-Password");
+                    easy_flipper_dialog("Error", "Failed to load Flip-Social-Password");
+                    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+                    return "Failed to load Flip-Social-Password";
+                }
+                // load wifi ssid,pass then save
+                char ssid[64];
+                char pass[64];
+                if (!load_char("WiFi-SSID", ssid, sizeof(ssid)))
+                {
+                    FURI_LOG_E(TAG, "Failed to load WiFi-SSID");
+                    easy_flipper_dialog("Error", "Failed to load WiFi-SSID");
+                    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+                    return "Failed to load WiFi-SSID";
+                }
+                if (!load_char("WiFi-Password", pass, sizeof(pass)))
+                {
+                    FURI_LOG_E(TAG, "Failed to load WiFi-Password");
+                    easy_flipper_dialog("Error", "Failed to load WiFi-Password");
+                    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+                    return "Failed to load WiFi-Password";
+                }
+                save_settings(ssid, pass, username, password);
+                model->title = "Fetching World List..";
+                return "Account created!";
+            }
+            else if (strstr(model->fhttp->last_response, "Username or password not provided") != NULL)
+            {
+                easy_flipper_dialog("Error", "Please enter your credentials.\nPress BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return "Please enter your credentials.";
+            }
+            else if (strstr(model->fhttp->last_response, "User already exists") != NULL || strstr(model->fhttp->last_response, "Multiple users found") != NULL)
+            {
+                easy_flipper_dialog("Error", "Registration failed...\nUsername already exists.\nPress BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return "Username already exists.";
+            }
+            else
+            {
+                easy_flipper_dialog("Error", "Registration failed...\nUpdate your credentials.\nPress BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return "Registration failed...";
+            }
+        }
+        else
+        {
+            if (!game_thread_start(app))
+            {
+                FURI_LOG_E(TAG, "Failed to start game thread");
+                easy_flipper_dialog("Error", "Failed to start game thread. Press BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher,
+                                               FlipWorldViewSubmenu); // just go back to the main menu for now
+                return "Failed to start game thread";
+            }
+            return "Thanks for playing FlipWorld!\n\n\n\nPress BACK to return if this\ndoesn't automatically close.";
+        }
+    }
+    else if (model->request_index == 2)
+    {
+        return "Welcome to FlipWorld!\n\n\n\nPress BACK to return if this\ndoesn't automatically close.";
+    }
+    else if (model->request_index == 3)
+    {
+        if (!game_thread_start(app))
+        {
+            FURI_LOG_E(TAG, "Failed to start game thread");
+            easy_flipper_dialog("Error", "Failed to start game thread. Press BACK to return.");
+            view_dispatcher_switch_to_view(app->view_dispatcher,
+                                           FlipWorldViewSubmenu); // just go back to the main menu for now
+            return "Failed to start game thread";
+        }
+        return "Thanks for playing FlipWorld!\n\n\n\nPress BACK to return if this\ndoesn't automatically close.";
+    }
+    easy_flipper_dialog("Error", "Unknown error. Press BACK to return.");
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu); // just go back to the main menu for now
+    return "Unknown error";
+}
+static void game_switch_to_view(FlipWorldApp *app)
+{
+    if (!loader_view_alloc(app))
+    {
+        FURI_LOG_E(TAG, "Failed to allocate view loader");
+        return;
+    }
+    loader_switch_to_view(app, "Starting Game..", game_fetch, game_parse, 5, callback_to_submenu, FlipWorldViewLoader);
+}
+bool game_start_ws(FlipperHTTP *fhttp, char *lobby_name)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    if (!lobby_name || strlen(lobby_name) == 0)
+    {
+        FURI_LOG_E(TAG, "Lobby name is NULL or empty");
+        return false;
+    }
+    fhttp->state = IDLE; // ensure it's set to IDLE for the next request
+    char websocket_url[128];
+    snprintf(websocket_url, sizeof(websocket_url), "ws://www.jblanked.com/ws/game/%s/", lobby_name);
+    if (!flipper_http_websocket_start(fhttp, websocket_url, 80, "{\"Content-Type\":\"application/json\"}"))
+    {
+        FURI_LOG_E(TAG, "Failed to start websocket");
+        return false;
+    }
+    fhttp->state = RECEIVING;
+    while (fhttp->state != IDLE)
+    {
+        furi_delay_ms(100);
+    }
+    return true;
+}
+// load pvp info (this returns the lobbies available)
+static bool game_fetch_lobbies(FlipperHTTP *fhttp, uint8_t max_players, uint8_t max_lobbies)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    char lobby_type[4];
+    snprintf(lobby_type, sizeof(lobby_type), game_mode_index == 0 ? "pve" : "pvp");
+    // ensure flip_world directory exists
+    char directory_path[128];
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world");
+    Storage *storage = furi_record_open(RECORD_STORAGE);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/%s", lobby_type);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/%s/lobbies", lobby_type);
+    storage_common_mkdir(storage, directory_path);
+    snprintf(fhttp->file_path, sizeof(fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/%s/%s_lobbies.json", lobby_type, lobby_type);
+    storage_simply_remove_recursive(storage, fhttp->file_path); // ensure the file is empty
+    furi_record_close(RECORD_STORAGE);
+    //
+    char url[128];
+    snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/world/%s/lobbies/%d/%d/", lobby_type, max_players, max_lobbies);
+    fhttp->save_received_data = true;
+    return flipper_http_request(fhttp, GET, url, "{\"Content-Type\":\"application/json\"}", NULL);
+}
+
+static bool game_parse_lobbies(FlipperHTTP *fhttp, uint8_t max_lobbies, void *context)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app);
+    // add the lobbies to the submenu
+    FuriString *lobbies = flipper_http_load_from_file(fhttp->file_path);
+    if (!lobbies)
+    {
+        FURI_LOG_E(TAG, "Failed to load lobbies");
+        return false;
+    }
+
+    // parse the lobbies
+    for (uint32_t i = 0; i < max_lobbies; i++)
+    {
+        FuriString *lobby = get_json_array_value_furi("lobbies", i, lobbies);
+        if (!lobby)
+        {
+            FURI_LOG_I(TAG, "No more lobbies");
+            break;
+        }
+        FuriString *lobby_id = get_json_value_furi("id", lobby);
+        if (!lobby_id)
+        {
+            FURI_LOG_E(TAG, "Failed to get lobby id");
+            furi_string_free(lobby);
+            return false;
+        }
+        // add the lobby to the submenu
+        submenu_add_item(app->submenu_other, furi_string_get_cstr(lobby_id), FlipWorldSubmenuIndexLobby + i, callback_submenu_lobby_pvp_choices, app);
+        // add the lobby to the list
+        if (!easy_flipper_set_buffer(&lobby_list[i], 64))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate lobby list");
+            furi_string_free(lobby);
+            furi_string_free(lobby_id);
+            return false;
+        }
+        snprintf(lobby_list[i], 64, "%s", furi_string_get_cstr(lobby_id));
+        furi_string_free(lobby);
+        furi_string_free(lobby_id);
+    }
+    furi_string_free(lobbies);
+    return true;
+}
+
+static bool game_lobbies(FlipperHTTP *fhttp, uint8_t max_players, uint8_t max_lobbies, void *context)
+{
+    if (!fhttp || !context)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP or context is NULL");
+        return false;
+    }
+    if (!game_fetch_lobbies(fhttp, max_players, max_lobbies))
+    {
+        FURI_LOG_E(TAG, "Failed to fetch lobbies");
+        return false;
+    }
+    fhttp->state = RECEIVING;
+    while (fhttp->state != IDLE)
+    {
+        // Wait for the request to be received
+        furi_delay_ms(100);
+    }
+    return game_parse_lobbies(fhttp, max_lobbies, context);
+}
+
+void game_run(FlipWorldApp *app)
+{
+    furi_check(app, "FlipWorldApp is NULL");
+    free_all_views(app, true, true, false);
+    // only need to check if they have 30k free (game needs about 12k currently)
+    if (!is_enough_heap(30000, false))
+    {
+        const size_t min_free = memmgr_get_free_heap();
+        char message[64];
+        snprintf(message, sizeof(message), "Not enough heap memory.\nThere are %zu bytes free.", min_free);
+        easy_flipper_dialog("Error", message);
+        return;
+    }
+    // check if logged in
+    if (is_logged_in() || is_logged_in_to_flip_social())
+    {
+        FlipperHTTP *fhttp = flipper_http_alloc();
+        if (!fhttp)
+        {
+            FURI_LOG_E(TAG, "Failed to allocate FlipperHTTP");
+            easy_flipper_dialog("Error", "Failed to allocate FlipperHTTP. Press BACK to return.");
+            return;
+        }
+        bool game_fetch_world_list_i()
+        {
+            return game_fetch_world_list(fhttp);
+        }
+        bool parse_world_list_i()
+        {
+            return fhttp->state != ISSUE;
+        }
+
+        bool game_fetch_player_stats_i()
+        {
+            return game_fetch_player_stats(fhttp);
+        }
+
+        if (!alloc_message_view(app, MessageStateLoading))
+        {
+            FURI_LOG_E(TAG, "Failed to allocate message view");
+            return;
+        }
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewMessage);
+
+        // Make the request
+        if (game_mode_index == 2) // GAME_MODE_STORY
+        {
+            if (!flipper_http_process_response_async(fhttp, game_fetch_world_list_i, parse_world_list_i) || !flipper_http_process_response_async(fhttp, game_fetch_player_stats_i, set_player_context))
+            {
+                FURI_LOG_E(HTTP_TAG, "Failed to make request");
+                flipper_http_free(fhttp);
+            }
+
+            flipper_http_free(fhttp);
+
+            if (!game_thread_start(app))
+            {
+                FURI_LOG_E(TAG, "Failed to start game thread");
+                easy_flipper_dialog("Error", "Failed to start game thread. Press BACK to return.");
+                return;
+            }
+        }
+        else
+        {
+            free_submenu_other(app);
+            if (!alloc_submenu_other(app, FlipWorldViewLobby))
+            {
+                FURI_LOG_E(TAG, "Failed to allocate lobby submenu");
+                return;
+            }
+
+            // load pvp lobbies and player stats
+            if (!game_lobbies(
+                    fhttp,
+                    game_mode_index == 1 ? 2 : MAX_ENEMIES,
+                    10,
+                    app))
+            {
+                // unlike the pve/story, receiving data is necessary
+                // so send the user back to the main menu if it fails
+                FURI_LOG_E(HTTP_TAG, "Failed to make request");
+                easy_flipper_dialog("Error", "Failed to make request. Press BACK to return.");
+                view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenu);
+                flipper_http_free(fhttp);
+            }
+            else
+            {
+                flipper_http_free(fhttp);
+
+                // switch to the lobby submenu
+                view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+            }
+        }
+    }
+    else
+    {
+        game_switch_to_view(app);
+    }
+}
+
+bool game_fetch_lobby(FlipperHTTP *fhttp, const char *lobby_name)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    if (!lobby_name || strlen(lobby_name) == 0)
+    {
+        FURI_LOG_E(TAG, "Lobby name is NULL or empty");
+        return false;
+    }
+    char lobby_type[4];
+    snprintf(lobby_type, sizeof(lobby_type), game_mode_index == 0 ? "pve" : "pvp");
+    char username[64];
+    if (!load_char("Flip-Social-Username", username, sizeof(username)))
+    {
+        FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+        return false;
+    }
+    // send the request to fetch the lobby details, with player_username
+    char url[128];
+    snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/world/%s/lobby/get/%s/%s/", lobby_type, lobby_name, username);
+    snprintf(fhttp->file_path, sizeof(fhttp->file_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/pvp/lobbies/%s.json", lobby_name);
+    fhttp->save_received_data = true;
+    if (!flipper_http_request(fhttp, GET, url, "{\"Content-Type\":\"application/json\"}", NULL))
+    {
+        FURI_LOG_E(TAG, "Failed to fetch lobby details");
+        return false;
+    }
+    fhttp->state = RECEIVING;
+    while (fhttp->state != IDLE)
+    {
+        furi_delay_ms(100);
+    }
+    return true;
+}
+bool game_join_lobby(FlipperHTTP *fhttp, const char *lobby_name)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    if (!lobby_name || strlen(lobby_name) == 0)
+    {
+        FURI_LOG_E(TAG, "Lobby name is NULL or empty");
+        return false;
+    }
+    char lobby_type[4];
+    snprintf(lobby_type, sizeof(lobby_type), game_mode_index == 0 ? "pve" : "pvp");
+    char username[64];
+    if (!load_char("Flip-Social-Username", username, sizeof(username)))
+    {
+        FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+        return false;
+    }
+    char url[128];
+    char payload[128];
+    snprintf(payload, sizeof(payload), "{\"username\":\"%s\", \"game_id\":\"%s\"}", username, lobby_name);
+    save_char("pvp_lobby_name", lobby_name); // save the lobby name
+    snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/world/%s/lobby/join/", lobby_type);
+    if (!flipper_http_request(fhttp, POST, url, "{\"Content-Type\":\"application/json\"}", payload))
+    {
+        FURI_LOG_E(TAG, "Failed to join lobby");
+        return false;
+    }
+    fhttp->state = RECEIVING;
+    while (fhttp->state != IDLE)
+    {
+        furi_delay_ms(100);
+    }
+    return true;
+}
+static bool game_create_pvp_enemy(FuriString *lobby_details)
+{
+    if (!lobby_details)
+    {
+        FURI_LOG_E(TAG, "Failed to load lobby details");
+        return false;
+    }
+
+    char current_user[64];
+    if (!load_char("Flip-Social-Username", current_user, sizeof(current_user)))
+    {
+        FURI_LOG_E(TAG, "Failed to load Flip-Social-Username");
+        save_char("create_pvp_error", "Failed to load Flip-Social-Username");
+        return false;
+    }
+
+    for (uint8_t i = 0; i < 2; i++)
+    {
+        // parse the lobby details
+        FuriString *player_stats = get_json_array_value_furi("player_stats", i, lobby_details);
+        if (!player_stats)
+        {
+            FURI_LOG_E(TAG, "Failed to get player stats");
+            save_char("create_pvp_error", "Failed to get player stats array");
+            return false;
+        }
+
+        // available keys from player_stats
+        FuriString *username = get_json_value_furi("username", player_stats);
+        if (!username)
+        {
+            FURI_LOG_E(TAG, "Failed to get username");
+            save_char("create_pvp_error", "Failed to get username");
+            furi_string_free(player_stats);
+            return false;
+        }
+
+        // check if the username is the same as the current user
+        if (is_str(furi_string_get_cstr(username), current_user))
+        {
+            furi_string_free(player_stats);
+            furi_string_free(username);
+            continue; // skip the current user
+        }
+
+        FuriString *strength = get_json_value_furi("strength", player_stats);
+        FuriString *health = get_json_value_furi("health", player_stats);
+        FuriString *attack_timer = get_json_value_furi("attack_timer", player_stats);
+
+        if (!strength || !health || !attack_timer)
+        {
+            FURI_LOG_E(TAG, "Failed to get player stats");
+            save_char("create_pvp_error", "Failed to get player stats");
+            furi_string_free(player_stats);
+            furi_string_free(username);
+            if (strength)
+                furi_string_free(strength);
+            if (health)
+                furi_string_free(health);
+            if (attack_timer)
+                furi_string_free(attack_timer);
+            return false;
+        }
+
+        // create enemy data
+        FuriString *enemy_data = furi_string_alloc();
+        furi_string_printf(
+            enemy_data,
+            "{\"enemy_data\":[{\"id\":\"sword\",\"is_user\":\"true\",\"username\":\"%s\","
+            "\"index\":0,\"start_position\":{\"x\":350,\"y\":210},\"end_position\":{\"x\":350,\"y\":210},"
+            "\"move_timer\":1,\"speed\":1,\"attack_timer\":%f,\"strength\":%f,\"health\":%f}]}",
+            furi_string_get_cstr(username),
+            (double)atof_furi(attack_timer),
+            (double)atof_furi(strength),
+            (double)atof_furi(health));
+
+        char directory_path[128];
+        snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world");
+        Storage *storage = furi_record_open(RECORD_STORAGE);
+        storage_common_mkdir(storage, directory_path);
+        snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds");
+        storage_common_mkdir(storage, directory_path);
+        snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/pvp_world");
+        storage_common_mkdir(storage, directory_path);
+        furi_record_close(RECORD_STORAGE);
+
+        snprintf(directory_path, sizeof(directory_path), STORAGE_EXT_PATH_PREFIX "/apps_data/flip_world/worlds/pvp_world/pvp_world_enemy_data.json");
+
+        // remove the enemy_data file if it exists
+        storage_simply_remove_recursive(storage, directory_path);
+
+        File *file = storage_file_alloc(storage);
+        if (!storage_file_open(file, directory_path, FSAM_WRITE, FSOM_CREATE_ALWAYS))
+        {
+            FURI_LOG_E("Game", "Failed to open file for writing: %s", directory_path);
+            save_char("create_pvp_error", "Failed to open file for writing");
+            storage_file_free(file);
+            furi_record_close(RECORD_STORAGE);
+            furi_string_free(enemy_data);
+            furi_string_free(player_stats);
+            furi_string_free(username);
+            furi_string_free(strength);
+            furi_string_free(health);
+            furi_string_free(attack_timer);
+            return false;
+        }
+
+        size_t data_size = furi_string_size(enemy_data);
+        if (storage_file_write(file, furi_string_get_cstr(enemy_data), data_size) != data_size)
+        {
+            FURI_LOG_E("Game", "Failed to write enemy_data");
+            save_char("create_pvp_error", "Failed to write enemy_data");
+        }
+        storage_file_close(file);
+
+        furi_string_free(enemy_data);
+        furi_string_free(player_stats);
+        furi_string_free(username);
+        furi_string_free(strength);
+        furi_string_free(health);
+        furi_string_free(attack_timer);
+
+        // player is found so break
+        break;
+    }
+
+    return true;
+}
+
+size_t game_lobby_count(FlipperHTTP *fhttp, FuriString *lobby)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return -1;
+    }
+    if (!lobby)
+    {
+        FURI_LOG_E(TAG, "Lobby details are NULL");
+        return -1;
+    }
+    // check if the player is in the lobby
+    FuriString *player_count = get_json_value_furi("player_count", lobby);
+    if (!player_count)
+    {
+        FURI_LOG_E(TAG, "Failed to get player count");
+        return -1;
+    }
+    const size_t count = atoi(furi_string_get_cstr(player_count));
+    furi_string_free(player_count);
+    return count;
+}
+bool game_in_lobby(FlipperHTTP *fhttp, FuriString *lobby)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    if (!lobby)
+    {
+        FURI_LOG_E(TAG, "Lobby details are NULL");
+        return false;
+    }
+    // check if the player is in the lobby
+    FuriString *is_in_game = get_json_value_furi("is_in_game", lobby);
+    if (!is_in_game)
+    {
+        FURI_LOG_E(TAG, "Failed to get is_in_game");
+        furi_string_free(is_in_game);
+        return false;
+    }
+    const bool in_game = is_str(furi_string_get_cstr(is_in_game), "true");
+    furi_string_free(is_in_game);
+    return in_game;
+}
+
+// this will free both the fhttp and lobby
+void game_start_game(FlipperHTTP *fhttp, FuriString *lobby, void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+
+    if (game_mode_index == 1) // pvp (in pve, we will apennd the enemies as they are read from the websocket)
+    {
+        // only thing left to do is create the enemy data and start the websocket session
+        if (!game_create_pvp_enemy(lobby))
+        {
+            FURI_LOG_E(TAG, "Failed to create pvp enemy context.");
+            easy_flipper_dialog("Error", "Failed to create pvp enemy context. Press BACK to return.");
+            flipper_http_free(fhttp);
+            furi_string_free(lobby);
+            return;
+        }
+    }
+    furi_string_free(lobby);
+
+    // used later in PVE mode if needed to fetch worlds
+    snprintf(game_ws_lobby_name, sizeof(game_ws_lobby_name), "%s", lobby_list[lobby_index]);
+
+    // start the websocket session
+    if (!game_start_ws(fhttp, game_ws_lobby_name))
+    {
+        FURI_LOG_E(TAG, "Failed to start websocket session");
+        easy_flipper_dialog("Error", "Failed to start websocket session. Press BACK to return.");
+        flipper_http_free(fhttp);
+        return;
+    }
+
+    flipper_http_free(fhttp);
+
+    // start the game thread
+    if (!game_thread_start(app))
+    {
+        FURI_LOG_E(TAG, "Failed to start game thread");
+        easy_flipper_dialog("Error", "Failed to start game thread. Press BACK to return.");
+        return;
+    }
+};
+void game_waiting_process(FlipperHTTP *fhttp, void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "Failed to allocate FlipperHTTP");
+        easy_flipper_dialog("Error", "Failed to allocate FlipperHTTP. Press BACK to return.");
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+        return;
+    }
+    // fetch the lobby details
+    if (!game_fetch_lobby(fhttp, lobby_list[lobby_index]))
+    {
+        FURI_LOG_E(TAG, "Failed to fetch lobby details");
+        flipper_http_free(fhttp);
+        easy_flipper_dialog("Error", "Failed to fetch lobby details. Press BACK to return.");
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+        return;
+    }
+    // load the lobby details
+    FuriString *lobby = flipper_http_load_from_file(fhttp->file_path);
+    if (!lobby)
+    {
+        FURI_LOG_E(TAG, "Failed to load lobby details");
+        flipper_http_free(fhttp);
+        easy_flipper_dialog("Error", "Failed to load lobby details. Press BACK to return.");
+        view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewSubmenuOther);
+        return;
+    }
+    // get the player count
+    const size_t count = game_lobby_count(fhttp, lobby);
+    if (count == 2)
+    {
+        // break out of this and start the game
+        game_start_game(fhttp, lobby, app); // this will free both the fhttp and lobby
+        return;
+    }
+    furi_string_free(lobby);
+}
+
+void game_waiting_lobby(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "waiting_lobby: FlipWorldApp is NULL");
+
+    if (!game_start_waiting_thread(app))
+    {
+        FURI_LOG_E(TAG, "Failed to start waiting thread");
+        easy_flipper_dialog("Error", "Failed to start waiting thread. Press BACK to return.");
+        return;
+    }
+
+    free_message_view(app);
+    if (!alloc_message_view(app, MessageStateWaitingLobby))
+    {
+        FURI_LOG_E(TAG, "Failed to allocate message view");
+        return;
+    }
+    // finally, switch to the waiting lobby view
+    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewMessage);
+};
+
+bool game_remove_from_lobby(FlipperHTTP *fhttp)
+{
+    if (!fhttp)
+    {
+        FURI_LOG_E(TAG, "FlipperHTTP is NULL");
+        return false;
+    }
+    char username[32];
+    if (!load_char("Flip-Social-Username", username, sizeof(username)))
+    {
+        FURI_LOG_E(TAG, "Failed to load data/Flip-Social-Username");
+        return false;
+    }
+    char lobby_type[4];
+    snprintf(lobby_type, sizeof(lobby_type), game_mode_index == 0 ? "pve" : "pvp");
+    char url[128];
+    char payload[128];
+    snprintf(payload, sizeof(payload), "{\"username\":\"%s\", \"game_id\":\"%s\"}", username, game_ws_lobby_name);
+    snprintf(url, sizeof(url), "https://www.jblanked.com/flipper/api/world/%s/lobby/remove/", lobby_type);
+    fhttp->state = IDLE;
+    if (!flipper_http_request(fhttp, POST, url, "{\"Content-Type\":\"application/json\"}", payload))
+    {
+        FURI_LOG_E(TAG, "Failed to remove player from lobby");
+        return false;
+    }
+    fhttp->state = RECEIVING;
+    while (fhttp->state != IDLE)
+    {
+        furi_delay_ms(100);
+    }
+    return true;
+}

+ 21 - 0
flip_world/callback/game.h

@@ -0,0 +1,21 @@
+#pragma once
+#include <flip_world.h>
+extern bool user_hit_back;
+extern uint32_t lobby_index;
+extern char *lobby_list[10];
+extern char game_ws_lobby_name[64];
+extern FuriThread *game_thread;
+extern FuriThread *waiting_thread;
+extern bool game_thread_running;
+extern bool waiting_thread_running;
+//
+bool game_start_ws(FlipperHTTP *fhttp, char *lobby_name);
+void game_run(FlipWorldApp *app);
+bool game_fetch_lobby(FlipperHTTP *fhttp, const char *lobby_name);
+bool game_join_lobby(FlipperHTTP *fhttp, const char *lobby_name);
+size_t game_lobby_count(FlipperHTTP *fhttp, FuriString *lobby);
+bool game_in_lobby(FlipperHTTP *fhttp, FuriString *lobby);
+void game_start_game(FlipperHTTP *fhttp, FuriString *lobby, void *context);
+void game_waiting_lobby(void *context);
+void game_waiting_process(FlipperHTTP *fhttp, void *context);
+bool game_remove_from_lobby(FlipperHTTP *fhttp);

+ 590 - 0
flip_world/callback/loader.c

@@ -0,0 +1,590 @@
+#include <callback/loader.h>
+#include <callback/utils.h>
+#include <alloc/alloc.h>
+
+bool loader_view_alloc(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    if (app->view_loader)
+    {
+        FURI_LOG_E(TAG, "View loader already allocated");
+        return false;
+    }
+    if (app->widget_result)
+    {
+        FURI_LOG_E(TAG, "Widget result already allocated");
+        return false;
+    }
+
+    view_dispatcher_set_custom_event_callback(app->view_dispatcher, loader_custom_event_callback);
+
+    if (!easy_flipper_set_view(&app->view_loader, FlipWorldViewLoader, loader_draw_callback, NULL, callback_to_submenu, &app->view_dispatcher, app))
+    {
+        return false;
+    }
+
+    loader_init(app->view_loader);
+
+    return easy_flipper_set_widget(&app->widget_result, FlipWorldViewWidgetResult, "", callback_to_submenu, &app->view_dispatcher);
+}
+
+void loader_view_free(void *context)
+{
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    furi_check(app, "FlipWorldApp is NULL");
+    // Free Widget(s)
+    if (app->widget_result)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewWidgetResult);
+        widget_free(app->widget_result);
+        app->widget_result = NULL;
+    }
+
+    // Free View(s)
+    if (app->view_loader)
+    {
+        view_dispatcher_remove_view(app->view_dispatcher, FlipWorldViewLoader);
+        loader_free_model(app->view_loader);
+        view_free(app->view_loader);
+        app->view_loader = NULL;
+    }
+}
+
+static void loader_error_draw(Canvas *canvas, DataLoaderModel *model)
+{
+    if (canvas == NULL)
+    {
+        FURI_LOG_E(TAG, "error_draw - canvas is NULL");
+        DEV_CRASH();
+        return;
+    }
+    if (model->fhttp->last_response != NULL)
+    {
+        if (strstr(model->fhttp->last_response, "[ERROR] Not connected to Wifi. Failed to reconnect.") != NULL)
+        {
+            canvas_clear(canvas);
+            canvas_draw_str(canvas, 0, 10, "[ERROR] Not connected to Wifi.");
+            canvas_draw_str(canvas, 0, 50, "Update your WiFi settings.");
+            canvas_draw_str(canvas, 0, 60, "Press BACK to return.");
+        }
+        else if (strstr(model->fhttp->last_response, "[ERROR] Failed to connect to Wifi.") != NULL)
+        {
+            canvas_clear(canvas);
+            canvas_draw_str(canvas, 0, 10, "[ERROR] Not connected to Wifi.");
+            canvas_draw_str(canvas, 0, 50, "Update your WiFi settings.");
+            canvas_draw_str(canvas, 0, 60, "Press BACK to return.");
+        }
+        else if (strstr(model->fhttp->last_response, "[ERROR] GET request failed or returned empty data.") != NULL)
+        {
+            canvas_clear(canvas);
+            canvas_draw_str(canvas, 0, 10, "[ERROR] WiFi error.");
+            canvas_draw_str(canvas, 0, 50, "Update your WiFi settings.");
+            canvas_draw_str(canvas, 0, 60, "Press BACK to return.");
+        }
+        else if (strstr(model->fhttp->last_response, "[PONG]") != NULL)
+        {
+            canvas_clear(canvas);
+            canvas_draw_str(canvas, 0, 10, "[STATUS]Connecting to AP...");
+        }
+        else
+        {
+            canvas_clear(canvas);
+            FURI_LOG_E(TAG, "Received an error: %s", model->fhttp->last_response);
+            canvas_draw_str(canvas, 0, 10, "[ERROR] Unusual error...");
+            canvas_draw_str(canvas, 0, 60, "Press BACK and retry.");
+        }
+    }
+    else
+    {
+        canvas_clear(canvas);
+        canvas_draw_str(canvas, 0, 10, "[ERROR] Unknown error.");
+        canvas_draw_str(canvas, 0, 50, "Update your WiFi settings.");
+        canvas_draw_str(canvas, 0, 60, "Press BACK to return.");
+    }
+}
+
+static void loader_process_callback(void *context)
+{
+    if (context == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_process_callback - context is NULL");
+        DEV_CRASH();
+        return;
+    }
+
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    View *view = app->view_loader;
+
+    DataState current_data_state;
+    DataLoaderModel *loader_model = NULL;
+    with_view_model(
+        view,
+        DataLoaderModel * model,
+        {
+            current_data_state = model->data_state;
+            loader_model = model;
+        },
+        false);
+    if (!loader_model || !loader_model->fhttp)
+    {
+        FURI_LOG_E(TAG, "Model or fhttp is NULL");
+        DEV_CRASH();
+        return;
+    }
+
+    if (current_data_state == DataStateInitial)
+    {
+        with_view_model(
+            view,
+            DataLoaderModel * model,
+            {
+                model->data_state = DataStateRequested;
+                DataLoaderFetch fetch = model->fetcher;
+                if (fetch == NULL)
+                {
+                    FURI_LOG_E(TAG, "Model doesn't have Fetch function assigned.");
+                    model->data_state = DataStateError;
+                    return;
+                }
+
+                // Clear any previous responses
+                strncpy(model->fhttp->last_response, "", 1);
+                bool request_status = fetch(model);
+                if (!request_status)
+                {
+                    model->data_state = DataStateError;
+                }
+            },
+            true);
+    }
+    else if (current_data_state == DataStateRequested || current_data_state == DataStateError)
+    {
+        if (loader_model->fhttp->state == IDLE && loader_model->fhttp->last_response != NULL)
+        {
+            if (strstr(loader_model->fhttp->last_response, "[PONG]") != NULL)
+            {
+                FURI_LOG_DEV(TAG, "PONG received.");
+            }
+            else if (strncmp(loader_model->fhttp->last_response, "[SUCCESS]", 9))
+            {
+                FURI_LOG_DEV(TAG, "SUCCESS received. %s", loader_model->fhttp->last_response ? loader_model->fhttp->last_response : "NULL");
+            }
+            else if (strncmp(loader_model->fhttp->last_response, "[ERROR]", 9))
+            {
+                FURI_LOG_DEV(TAG, "ERROR received. %s", loader_model->fhttp->last_response ? loader_model->fhttp->last_response : "NULL");
+            }
+            else if (strlen(loader_model->fhttp->last_response))
+            {
+                // Still waiting on response
+            }
+            else
+            {
+                with_view_model(view, DataLoaderModel * model, { model->data_state = DataStateReceived; }, true);
+            }
+        }
+        else if (loader_model->fhttp->state == SENDING || loader_model->fhttp->state == RECEIVING)
+        {
+            // continue waiting
+        }
+        else if (loader_model->fhttp->state == INACTIVE)
+        {
+            // inactive. try again
+        }
+        else if (loader_model->fhttp->state == ISSUE)
+        {
+            with_view_model(view, DataLoaderModel * model, { model->data_state = DataStateError; }, true);
+        }
+        else
+        {
+            FURI_LOG_DEV(TAG, "Unexpected state: %d lastresp: %s", loader_model->fhttp->state, loader_model->fhttp->last_response ? loader_model->fhttp->last_response : "NULL");
+            DEV_CRASH();
+        }
+    }
+    else if (current_data_state == DataStateReceived)
+    {
+        with_view_model(
+            view,
+            DataLoaderModel * model,
+            {
+                char *data_text;
+                if (model->parser == NULL)
+                {
+                    data_text = NULL;
+                    FURI_LOG_DEV(TAG, "Parser is NULL");
+                    DEV_CRASH();
+                }
+                else
+                {
+                    data_text = model->parser(model);
+                }
+                FURI_LOG_DEV(TAG, "Parsed data: %s\r\ntext: %s", model->fhttp->last_response ? model->fhttp->last_response : "NULL", data_text ? data_text : "NULL");
+                model->data_text = data_text;
+                if (data_text == NULL)
+                {
+                    model->data_state = DataStateParseError;
+                }
+                else
+                {
+                    model->data_state = DataStateParsed;
+                }
+            },
+            true);
+    }
+    else if (current_data_state == DataStateParsed)
+    {
+        with_view_model(
+            view,
+            DataLoaderModel * model,
+            {
+                if (++model->request_index < model->request_count)
+                {
+                    model->data_state = DataStateInitial;
+                }
+                else
+                {
+                    loader_widget_set_text(model->data_text != NULL ? model->data_text : "", &app->widget_result);
+                    if (model->data_text != NULL)
+                    {
+                        free(model->data_text);
+                        model->data_text = NULL;
+                    }
+                    view_set_previous_callback(widget_get_view(app->widget_result), model->back_callback);
+                    view_dispatcher_switch_to_view(app->view_dispatcher, FlipWorldViewWidgetResult);
+                }
+            },
+            true);
+    }
+}
+
+bool loader_custom_event_callback(void *context, uint32_t index)
+{
+    if (context == NULL)
+    {
+        FURI_LOG_E(TAG, "custom_event_callback - context is NULL");
+        DEV_CRASH();
+        return false;
+    }
+
+    switch (index)
+    {
+    case FlipWorldCustomEventProcess:
+        loader_process_callback(context);
+        return true;
+    default:
+        FURI_LOG_DEV(TAG, "custom_event_callback. Unknown index: %ld", index);
+        return false;
+    }
+}
+
+void loader_draw_callback(Canvas *canvas, void *model)
+{
+    if (!canvas || !model)
+    {
+        FURI_LOG_E(TAG, "loader_draw_callback - canvas or model is NULL");
+        return;
+    }
+
+    DataLoaderModel *data_loader_model = (DataLoaderModel *)model;
+    HTTPState http_state = data_loader_model->fhttp->state;
+    DataState data_state = data_loader_model->data_state;
+    char *title = data_loader_model->title;
+
+    canvas_set_font(canvas, FontSecondary);
+
+    if (http_state == INACTIVE)
+    {
+        canvas_draw_str(canvas, 0, 7, "Wifi Dev Board disconnected.");
+        canvas_draw_str(canvas, 0, 17, "Please connect to the board.");
+        canvas_draw_str(canvas, 0, 32, "If your board is connected,");
+        canvas_draw_str(canvas, 0, 42, "make sure you have flashed");
+        canvas_draw_str(canvas, 0, 52, "your WiFi Devboard with the");
+        canvas_draw_str(canvas, 0, 62, "latest FlipperHTTP flash.");
+        return;
+    }
+
+    if (data_state == DataStateError || data_state == DataStateParseError)
+    {
+        loader_error_draw(canvas, data_loader_model);
+        return;
+    }
+
+    canvas_draw_str(canvas, 0, 7, title);
+    canvas_draw_str(canvas, 0, 17, "Loading...");
+
+    if (data_state == DataStateInitial)
+    {
+        return;
+    }
+
+    if (http_state == SENDING)
+    {
+        canvas_draw_str(canvas, 0, 27, "Fetching...");
+        return;
+    }
+
+    if (http_state == RECEIVING || data_state == DataStateRequested)
+    {
+        canvas_draw_str(canvas, 0, 27, "Receiving...");
+        return;
+    }
+
+    if (http_state == IDLE && data_state == DataStateReceived)
+    {
+        canvas_draw_str(canvas, 0, 27, "Processing...");
+        return;
+    }
+
+    if (http_state == IDLE && data_state == DataStateParsed)
+    {
+        canvas_draw_str(canvas, 0, 27, "Processed...");
+        return;
+    }
+}
+
+static void loader_timer_callback(void *context)
+{
+    if (context == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_timer_callback - context is NULL");
+        DEV_CRASH();
+        return;
+    }
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    view_dispatcher_send_custom_event(app->view_dispatcher, FlipWorldCustomEventProcess);
+}
+
+static void loader_on_enter(void *context)
+{
+    if (context == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_on_enter - context is NULL");
+        DEV_CRASH();
+        return;
+    }
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    View *view = app->view_loader;
+    with_view_model(
+        view,
+        DataLoaderModel * model,
+        {
+            view_set_previous_callback(view, model->back_callback);
+            if (model->timer == NULL)
+            {
+                model->timer = furi_timer_alloc(loader_timer_callback, FuriTimerTypePeriodic, app);
+            }
+            furi_timer_start(model->timer, 250);
+        },
+        true);
+}
+
+static void loader_on_exit(void *context)
+{
+    if (context == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_on_exit - context is NULL");
+        DEV_CRASH();
+        return;
+    }
+    FlipWorldApp *app = (FlipWorldApp *)context;
+    View *view = app->view_loader;
+    with_view_model(
+        view,
+        DataLoaderModel * model,
+        {
+            if (model->timer)
+            {
+                furi_timer_stop(model->timer);
+            }
+        },
+        false);
+}
+
+void loader_init(View *view)
+{
+    if (view == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_init - view is NULL");
+        DEV_CRASH();
+        return;
+    }
+    view_allocate_model(view, ViewModelTypeLocking, sizeof(DataLoaderModel));
+    view_set_enter_callback(view, loader_on_enter);
+    view_set_exit_callback(view, loader_on_exit);
+}
+
+void loader_free_model(View *view)
+{
+    if (view == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_free_model - view is NULL");
+        DEV_CRASH();
+        return;
+    }
+    with_view_model(
+        view,
+        DataLoaderModel * model,
+        {
+            if (model->timer)
+            {
+                furi_timer_free(model->timer);
+                model->timer = NULL;
+            }
+            if (model->parser_context)
+            {
+                // do not free the context here, it is the app context
+                // free(model->parser_context);
+                // model->parser_context = NULL;
+            }
+            if (model->fhttp)
+            {
+                flipper_http_free(model->fhttp);
+                model->fhttp = NULL;
+            }
+        },
+        false);
+}
+
+void loader_switch_to_view(FlipWorldApp *app, char *title, DataLoaderFetch fetcher, DataLoaderParser parser, size_t request_count, ViewNavigationCallback back, uint32_t view_id)
+{
+    if (app == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_switch_to_view - app is NULL");
+        DEV_CRASH();
+        return;
+    }
+
+    View *view = app->view_loader;
+    if (view == NULL)
+    {
+        FURI_LOG_E(TAG, "loader_switch_to_view - view is NULL");
+        DEV_CRASH();
+        return;
+    }
+
+    with_view_model(
+        view,
+        DataLoaderModel * model,
+        {
+            model->title = title;
+            model->fetcher = fetcher;
+            model->parser = parser;
+            model->request_index = 0;
+            model->request_count = request_count;
+            model->back_callback = back;
+            model->data_state = DataStateInitial;
+            model->data_text = NULL;
+            //
+            model->parser_context = app;
+            if (!model->fhttp)
+            {
+                model->fhttp = flipper_http_alloc();
+            }
+        },
+        true);
+
+    view_dispatcher_switch_to_view(app->view_dispatcher, view_id);
+}
+
+void loader_widget_set_text(char *message, Widget **widget)
+{
+    if (widget == NULL)
+    {
+        FURI_LOG_E(TAG, "set_widget_text - widget is NULL");
+        DEV_CRASH();
+        return;
+    }
+    if (message == NULL)
+    {
+        FURI_LOG_E(TAG, "set_widget_text - message is NULL");
+        DEV_CRASH();
+        return;
+    }
+    widget_reset(*widget);
+
+    uint32_t message_length = strlen(message); // Length of the message
+    uint32_t i = 0;                            // Index tracker
+    uint32_t formatted_index = 0;              // Tracker for where we are in the formatted message
+    char *formatted_message;                   // Buffer to hold the final formatted message
+
+    // Allocate buffer with double the message length plus one for safety
+    if (!easy_flipper_set_buffer(&formatted_message, message_length * 2 + 1))
+    {
+        return;
+    }
+
+    while (i < message_length)
+    {
+        uint32_t max_line_length = 31;                  // Maximum characters per line
+        uint32_t remaining_length = message_length - i; // Remaining characters
+        uint32_t line_length = (remaining_length < max_line_length) ? remaining_length : max_line_length;
+
+        // Check for newline character within the current segment
+        uint32_t newline_pos = i;
+        bool found_newline = false;
+        for (; newline_pos < i + line_length && newline_pos < message_length; newline_pos++)
+        {
+            if (message[newline_pos] == '\n')
+            {
+                found_newline = true;
+                break;
+            }
+        }
+
+        if (found_newline)
+        {
+            // If newline found, set line_length up to the newline
+            line_length = newline_pos - i;
+        }
+
+        // Temporary buffer to hold the current line
+        char line[32];
+        strncpy(line, message + i, line_length);
+        line[line_length] = '\0';
+
+        // If newline was found, skip it for the next iteration
+        if (found_newline)
+        {
+            i += line_length + 1; // +1 to skip the '\n' character
+        }
+        else
+        {
+            // Check if the line ends in the middle of a word and adjust accordingly
+            if (line_length == max_line_length && message[i + line_length] != '\0' && message[i + line_length] != ' ')
+            {
+                // Find the last space within the current line to avoid breaking a word
+                char *last_space = strrchr(line, ' ');
+                if (last_space != NULL)
+                {
+                    // Adjust the line_length to avoid cutting the word
+                    line_length = last_space - line;
+                    line[line_length] = '\0'; // Null-terminate at the space
+                }
+            }
+
+            // Move the index forward by the determined line_length
+            i += line_length;
+
+            // Skip any spaces at the beginning of the next line
+            while (i < message_length && message[i] == ' ')
+            {
+                i++;
+            }
+        }
+
+        // Manually copy the fixed line into the formatted_message buffer
+        for (uint32_t j = 0; j < line_length; j++)
+        {
+            formatted_message[formatted_index++] = line[j];
+        }
+
+        // Add a newline character for line spacing
+        formatted_message[formatted_index++] = '\n';
+    }
+
+    // Null-terminate the formatted_message
+    formatted_message[formatted_index] = '\0';
+
+    // Add the formatted message to the widget
+    widget_add_text_scroll_element(*widget, 0, 0, 128, 64, formatted_message);
+}

+ 39 - 0
flip_world/callback/loader.h

@@ -0,0 +1,39 @@
+#pragma once
+#include <flip_world.h>
+
+typedef enum DataState DataState;
+enum DataState
+{
+    DataStateInitial,
+    DataStateRequested,
+    DataStateReceived,
+    DataStateParsed,
+    DataStateParseError,
+    DataStateError,
+};
+
+typedef struct DataLoaderModel DataLoaderModel;
+typedef bool (*DataLoaderFetch)(DataLoaderModel *model);
+typedef char *(*DataLoaderParser)(DataLoaderModel *model);
+struct DataLoaderModel
+{
+    char *title;
+    char *data_text;
+    DataState data_state;
+    DataLoaderFetch fetcher;
+    DataLoaderParser parser;
+    void *parser_context;
+    size_t request_index;
+    size_t request_count;
+    ViewNavigationCallback back_callback;
+    FuriTimer *timer;
+    FlipperHTTP *fhttp;
+};
+bool loader_view_alloc(void *context);
+void loader_view_free(void *context);
+void loader_switch_to_view(FlipWorldApp *app, char *title, DataLoaderFetch fetcher, DataLoaderParser parser, size_t request_count, ViewNavigationCallback back, uint32_t view_id);
+void loader_draw_callback(Canvas *canvas, void *model);
+void loader_init(View *view);
+void loader_widget_set_text(char *message, Widget **widget);
+void loader_free_model(View *view);
+bool loader_custom_event_callback(void *context, uint32_t index);

+ 25 - 0
flip_world/callback/utils.h

@@ -0,0 +1,25 @@
+#pragma once
+#include <flip_world.h>
+
+// Below added by Derek Jamison
+// FURI_LOG_DEV will log only during app development. Be sure that Settings/System/Log Device is "LPUART"; so we dont use serial port.
+#ifdef DEVELOPMENT
+#define FURI_LOG_DEV(tag, format, ...) furi_log_print_format(FuriLogLevelInfo, tag, format, ##__VA_ARGS__)
+#define DEV_CRASH() furi_crash()
+#else
+#define FURI_LOG_DEV(tag, format, ...)
+#define DEV_CRASH()
+#endif
+
+typedef enum MessageState MessageState;
+enum MessageState
+{
+    MessageStateAbout,        // The about screen
+    MessageStateLoading,      // The loading screen (for game)
+    MessageStateWaitingLobby, // The waiting lobby screen
+};
+typedef struct MessageModel MessageModel;
+struct MessageModel
+{
+    MessageState message_state;
+};

+ 626 - 0
flip_world/easy_flipper/easy_flipper.c

@@ -0,0 +1,626 @@
+#include <easy_flipper/easy_flipper.h>
+
+void easy_flipper_dialog(
+    char *header,
+    char *text)
+{
+    DialogsApp *dialogs = furi_record_open(RECORD_DIALOGS);
+    DialogMessage *message = dialog_message_alloc();
+    dialog_message_set_header(
+        message, header, 64, 0, AlignCenter, AlignTop);
+    dialog_message_set_text(
+        message,
+        text,
+        0,
+        63,
+        AlignLeft,
+        AlignBottom);
+    dialog_message_show(dialogs, message);
+    dialog_message_free(message);
+    furi_record_close(RECORD_DIALOGS);
+}
+
+/**
+ * @brief Navigation callback for exiting the application
+ * @param context The context - unused
+ * @return next view id (VIEW_NONE to exit the app)
+ */
+uint32_t easy_flipper_callback_exit_app(void *context)
+{
+    // Exit the application
+    if (!context)
+    {
+        FURI_LOG_E(EASY_TAG, "Context is NULL");
+        return VIEW_NONE;
+    }
+    UNUSED(context);
+    return VIEW_NONE; // Return VIEW_NONE to exit the app
+}
+
+/**
+ * @brief Initialize a buffer
+ * @param buffer The buffer to initialize
+ * @param buffer_size The size of the buffer
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_buffer(char **buffer, uint32_t buffer_size)
+{
+    if (!buffer)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_buffer");
+        return false;
+    }
+    *buffer = (char *)malloc(buffer_size);
+    if (!*buffer)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate buffer");
+        return false;
+    }
+    *buffer[0] = '\0';
+    return true;
+}
+
+/**
+ * @brief Initialize a View object
+ * @param view The View object to initialize
+ * @param view_id The ID/Index of the view
+ * @param draw_callback The draw callback function (set to NULL if not needed)
+ * @param input_callback The input callback function (set to NULL if not needed)
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_view(
+    View **view,
+    int32_t view_id,
+    void draw_callback(Canvas *, void *),
+    bool input_callback(InputEvent *, void *),
+    uint32_t (*previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!view || !view_dispatcher)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_view");
+        return false;
+    }
+    *view = view_alloc();
+    if (!*view)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate View");
+        return false;
+    }
+    if (draw_callback)
+    {
+        view_set_draw_callback(*view, draw_callback);
+    }
+    if (input_callback)
+    {
+        view_set_input_callback(*view, input_callback);
+    }
+    if (context)
+    {
+        view_set_context(*view, context);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(*view, previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, *view);
+    return true;
+}
+
+/**
+ * @brief Initialize a ViewDispatcher object
+ * @param view_dispatcher The ViewDispatcher object to initialize
+ * @param gui The GUI object
+ * @param context The context to pass to the event callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_view_dispatcher(ViewDispatcher **view_dispatcher, Gui *gui, void *context)
+{
+    if (!view_dispatcher)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_view_dispatcher");
+        return false;
+    }
+    *view_dispatcher = view_dispatcher_alloc();
+    if (!*view_dispatcher)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate ViewDispatcher");
+        return false;
+    }
+    view_dispatcher_attach_to_gui(*view_dispatcher, gui, ViewDispatcherTypeFullscreen);
+    if (context)
+    {
+        view_dispatcher_set_event_callback_context(*view_dispatcher, context);
+    }
+    return true;
+}
+
+/**
+ * @brief Initialize a Submenu object
+ * @note This does not set the items in the submenu
+ * @param submenu The Submenu object to initialize
+ * @param view_id The ID/Index of the view
+ * @param title The title/header of the submenu
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_submenu(
+    Submenu **submenu,
+    int32_t view_id,
+    char *title,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher)
+{
+    if (!submenu)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_submenu");
+        return false;
+    }
+    *submenu = submenu_alloc();
+    if (!*submenu)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate Submenu");
+        return false;
+    }
+    if (title)
+    {
+        submenu_set_header(*submenu, title);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(submenu_get_view(*submenu), previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, submenu_get_view(*submenu));
+    return true;
+}
+/**
+ * @brief Initialize a Menu object
+ * @note This does not set the items in the menu
+ * @param menu The Menu object to initialize
+ * @param view_id The ID/Index of the view
+ * @param item_callback The item callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_menu(
+    Menu **menu,
+    int32_t view_id,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher)
+{
+    if (!menu)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_menu");
+        return false;
+    }
+    *menu = menu_alloc();
+    if (!*menu)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate Menu");
+        return false;
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(menu_get_view(*menu), previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, menu_get_view(*menu));
+    return true;
+}
+
+/**
+ * @brief Initialize a Widget object
+ * @param widget The Widget object to initialize
+ * @param view_id The ID/Index of the view
+ * @param text The text to display in the widget
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_widget(
+    Widget **widget,
+    int32_t view_id,
+    char *text,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher)
+{
+    if (!widget)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_widget");
+        return false;
+    }
+    *widget = widget_alloc();
+    if (!*widget)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate Widget");
+        return false;
+    }
+    if (text)
+    {
+        widget_add_text_scroll_element(*widget, 0, 0, 128, 64, text);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(widget_get_view(*widget), previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, widget_get_view(*widget));
+    return true;
+}
+
+/**
+ * @brief Initialize a VariableItemList object
+ * @note This does not set the items in the VariableItemList
+ * @param variable_item_list The VariableItemList object to initialize
+ * @param view_id The ID/Index of the view
+ * @param enter_callback The enter callback function (can be set to NULL)
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the enter callback (usually the app)
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_variable_item_list(
+    VariableItemList **variable_item_list,
+    int32_t view_id,
+    void (*enter_callback)(void *, uint32_t),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!variable_item_list)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_variable_item_list");
+        return false;
+    }
+    *variable_item_list = variable_item_list_alloc();
+    if (!*variable_item_list)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate VariableItemList");
+        return false;
+    }
+    if (enter_callback)
+    {
+        variable_item_list_set_enter_callback(*variable_item_list, enter_callback, context);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(variable_item_list_get_view(*variable_item_list), previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, variable_item_list_get_view(*variable_item_list));
+    return true;
+}
+
+/**
+ * @brief Initialize a TextInput object
+ * @param text_input The TextInput object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_text_input(
+    TextInput **text_input,
+    int32_t view_id,
+    char *header_text,
+    char *text_input_temp_buffer,
+    uint32_t text_input_buffer_size,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!text_input)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_text_input");
+        return false;
+    }
+    *text_input = text_input_alloc();
+    if (!*text_input)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate TextInput");
+        return false;
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(text_input_get_view(*text_input), previous_callback);
+    }
+    if (header_text)
+    {
+        text_input_set_header_text(*text_input, header_text);
+    }
+    if (text_input_temp_buffer && text_input_buffer_size && result_callback)
+    {
+        text_input_set_result_callback(*text_input, result_callback, context, text_input_temp_buffer, text_input_buffer_size, false);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, text_input_get_view(*text_input));
+    return true;
+}
+
+/**
+ * @brief Initialize a UART_TextInput object
+ * @param uart_text_input The UART_TextInput object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_uart_text_input(
+    UART_TextInput **uart_text_input,
+    int32_t view_id,
+    char *header_text,
+    char *uart_text_input_temp_buffer,
+    uint32_t uart_text_input_buffer_size,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!uart_text_input)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_uart_text_input");
+        return false;
+    }
+    *uart_text_input = uart_text_input_alloc();
+    if (!*uart_text_input)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate UART_TextInput");
+        return false;
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(uart_text_input_get_view(*uart_text_input), previous_callback);
+    }
+    if (header_text)
+    {
+        uart_text_input_set_header_text(*uart_text_input, header_text);
+    }
+    if (uart_text_input_temp_buffer && uart_text_input_buffer_size && result_callback)
+    {
+        uart_text_input_set_result_callback(*uart_text_input, result_callback, context, uart_text_input_temp_buffer, uart_text_input_buffer_size, false);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, uart_text_input_get_view(*uart_text_input));
+    return true;
+}
+
+/**
+ * @brief Initialize a DialogEx object
+ * @param dialog_ex The DialogEx object to initialize
+ * @param view_id The ID/Index of the view
+ * @param header The header of the dialog
+ * @param header_x The x coordinate of the header
+ * @param header_y The y coordinate of the header
+ * @param text The text of the dialog
+ * @param text_x The x coordinate of the dialog
+ * @param text_y The y coordinate of the dialog
+ * @param left_button_text The text of the left button
+ * @param right_button_text The text of the right button
+ * @param center_button_text The text of the center button
+ * @param result_callback The result callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the result callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_dialog_ex(
+    DialogEx **dialog_ex,
+    int32_t view_id,
+    char *header,
+    uint16_t header_x,
+    uint16_t header_y,
+    char *text,
+    uint16_t text_x,
+    uint16_t text_y,
+    char *left_button_text,
+    char *right_button_text,
+    char *center_button_text,
+    void (*result_callback)(DialogExResult, void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!dialog_ex)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_dialog_ex");
+        return false;
+    }
+    *dialog_ex = dialog_ex_alloc();
+    if (!*dialog_ex)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate DialogEx");
+        return false;
+    }
+    if (header)
+    {
+        dialog_ex_set_header(*dialog_ex, header, header_x, header_y, AlignLeft, AlignTop);
+    }
+    if (text)
+    {
+        dialog_ex_set_text(*dialog_ex, text, text_x, text_y, AlignLeft, AlignTop);
+    }
+    if (left_button_text)
+    {
+        dialog_ex_set_left_button_text(*dialog_ex, left_button_text);
+    }
+    if (right_button_text)
+    {
+        dialog_ex_set_right_button_text(*dialog_ex, right_button_text);
+    }
+    if (center_button_text)
+    {
+        dialog_ex_set_center_button_text(*dialog_ex, center_button_text);
+    }
+    if (result_callback)
+    {
+        dialog_ex_set_result_callback(*dialog_ex, result_callback);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(dialog_ex_get_view(*dialog_ex), previous_callback);
+    }
+    if (context)
+    {
+        dialog_ex_set_context(*dialog_ex, context);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, dialog_ex_get_view(*dialog_ex));
+    return true;
+}
+
+/**
+ * @brief Initialize a Popup object
+ * @param popup The Popup object to initialize
+ * @param view_id The ID/Index of the view
+ * @param header The header of the dialog
+ * @param header_x The x coordinate of the header
+ * @param header_y The y coordinate of the header
+ * @param text The text of the dialog
+ * @param text_x The x coordinate of the dialog
+ * @param text_y The y coordinate of the dialog
+ * @param result_callback The result callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the result callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_popup(
+    Popup **popup,
+    int32_t view_id,
+    char *header,
+    uint16_t header_x,
+    uint16_t header_y,
+    char *text,
+    uint16_t text_x,
+    uint16_t text_y,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context)
+{
+    if (!popup)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_popup");
+        return false;
+    }
+    *popup = popup_alloc();
+    if (!*popup)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate Popup");
+        return false;
+    }
+    if (header)
+    {
+        popup_set_header(*popup, header, header_x, header_y, AlignLeft, AlignTop);
+    }
+    if (text)
+    {
+        popup_set_text(*popup, text, text_x, text_y, AlignLeft, AlignTop);
+    }
+    if (result_callback)
+    {
+        popup_set_callback(*popup, result_callback);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(popup_get_view(*popup), previous_callback);
+    }
+    if (context)
+    {
+        popup_set_context(*popup, context);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, popup_get_view(*popup));
+    return true;
+}
+
+/**
+ * @brief Initialize a Loading object
+ * @param loading The Loading object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_loading(
+    Loading **loading,
+    int32_t view_id,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher)
+{
+    if (!loading)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_loading");
+        return false;
+    }
+    *loading = loading_alloc();
+    if (!*loading)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate Loading");
+        return false;
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(loading_get_view(*loading), previous_callback);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, loading_get_view(*loading));
+    return true;
+}
+
+/**
+ * @brief Set a char butter to a FuriString
+ * @param furi_string The FuriString object
+ * @param buffer The buffer to copy the string to
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_char_to_furi_string(FuriString **furi_string, char *buffer)
+{
+    if (!furi_string)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_buffer_to_furi_string");
+        return false;
+    }
+    *furi_string = furi_string_alloc();
+    if (!furi_string)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate FuriString");
+        return false;
+    }
+    furi_string_set_str(*furi_string, buffer);
+    return true;
+}
+
+bool easy_flipper_set_text_box(
+    TextBox **text_box,
+    int32_t view_id,
+    char *text,
+    bool start_at_end,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher)
+{
+    if (!text_box)
+    {
+        FURI_LOG_E(EASY_TAG, "Invalid arguments provided to set_text_box");
+        return false;
+    }
+    *text_box = text_box_alloc();
+    if (!*text_box)
+    {
+        FURI_LOG_E(EASY_TAG, "Failed to allocate TextBox");
+        return false;
+    }
+    if (text)
+    {
+        text_box_set_text(*text_box, text);
+    }
+    if (previous_callback)
+    {
+        view_set_previous_callback(text_box_get_view(*text_box), previous_callback);
+    }
+    text_box_set_font(*text_box, TextBoxFontText);
+    if (start_at_end)
+    {
+        text_box_set_focus(*text_box, TextBoxFocusEnd);
+    }
+    view_dispatcher_add_view(*view_dispatcher, view_id, text_box_get_view(*text_box));
+    return true;
+}

+ 296 - 0
flip_world/easy_flipper/easy_flipper.h

@@ -0,0 +1,296 @@
+#ifndef EASY_FLIPPER_H
+#define EASY_FLIPPER_H
+
+#include <malloc.h>
+#include <furi.h>
+#include <furi_hal.h>
+#include <gui/gui.h>
+#include <gui/view.h>
+#include <gui/modules/submenu.h>
+#include <gui/view_dispatcher.h>
+#include <gui/elements.h>
+#include <gui/modules/menu.h>
+#include <gui/modules/submenu.h>
+#include <gui/modules/widget.h>
+#include <gui/modules/text_input.h>
+#include <gui/modules/text_box.h>
+#include <gui/modules/variable_item_list.h>
+#include <gui/modules/dialog_ex.h>
+#include <notification/notification.h>
+#include <dialogs/dialogs.h>
+#include <gui/modules/popup.h>
+#include <gui/modules/loading.h>
+#include <text_input/uart_text_input.h>
+#include <stdio.h>
+#include <string.h>
+#include <jsmn/jsmn_furi.h>
+#include <jsmn/jsmn.h>
+
+// added by Derek Jamison to lower memory usage
+#undef FURI_LOG_E
+#define FURI_LOG_E(tag, msg, ...)
+
+#undef FURI_LOG_I
+#define FURI_LOG_I(tag, msg, ...)
+//
+
+#define EASY_TAG "EasyFlipper"
+
+void easy_flipper_dialog(
+    char *header,
+    char *text);
+
+/**
+ * @brief Navigation callback for exiting the application
+ * @param context The context - unused
+ * @return next view id (VIEW_NONE to exit the app)
+ */
+uint32_t easy_flipper_callback_exit_app(void *context);
+/**
+ * @brief Initialize a buffer
+ * @param buffer The buffer to initialize
+ * @param buffer_size The size of the buffer
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_buffer(char **buffer, uint32_t buffer_size);
+/**
+ * @brief Initialize a View object
+ * @param view The View object to initialize
+ * @param view_id The ID/Index of the view
+ * @param draw_callback The draw callback function (set to NULL if not needed)
+ * @param input_callback The input callback function (set to NULL if not needed)
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_view(
+    View **view,
+    int32_t view_id,
+    void draw_callback(Canvas *, void *),
+    bool input_callback(InputEvent *, void *),
+    uint32_t (*previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a ViewDispatcher object
+ * @param view_dispatcher The ViewDispatcher object to initialize
+ * @param gui The GUI object
+ * @param context The context to pass to the event callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_view_dispatcher(ViewDispatcher **view_dispatcher, Gui *gui, void *context);
+
+/**
+ * @brief Initialize a Submenu object
+ * @note This does not set the items in the submenu
+ * @param submenu The Submenu object to initialize
+ * @param view_id The ID/Index of the view
+ * @param title The title/header of the submenu
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_submenu(
+    Submenu **submenu,
+    int32_t view_id,
+    char *title,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher);
+
+/**
+ * @brief Initialize a Menu object
+ * @note This does not set the items in the menu
+ * @param menu The Menu object to initialize
+ * @param view_id The ID/Index of the view
+ * @param item_callback The item callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_menu(
+    Menu **menu,
+    int32_t view_id,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher);
+
+/**
+ * @brief Initialize a Widget object
+ * @param widget The Widget object to initialize
+ * @param view_id The ID/Index of the view
+ * @param text The text to display in the widget
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_widget(
+    Widget **widget,
+    int32_t view_id,
+    char *text,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher);
+
+/**
+ * @brief Initialize a VariableItemList object
+ * @note This does not set the items in the VariableItemList
+ * @param variable_item_list The VariableItemList object to initialize
+ * @param view_id The ID/Index of the view
+ * @param enter_callback The enter callback function (can be set to NULL)
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the enter callback (usually the app)
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_variable_item_list(
+    VariableItemList **variable_item_list,
+    int32_t view_id,
+    void (*enter_callback)(void *, uint32_t),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a TextInput object
+ * @param text_input The TextInput object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_text_input(
+    TextInput **text_input,
+    int32_t view_id,
+    char *header_text,
+    char *text_input_temp_buffer,
+    uint32_t text_input_buffer_size,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a UART_TextInput object
+ * @param uart_text_input The UART_TextInput object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_uart_text_input(
+    UART_TextInput **uart_text_input,
+    int32_t view_id,
+    char *header_text,
+    char *uart_text_input_temp_buffer,
+    uint32_t uart_text_input_buffer_size,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a DialogEx object
+ * @param dialog_ex The DialogEx object to initialize
+ * @param view_id The ID/Index of the view
+ * @param header The header of the dialog
+ * @param header_x The x coordinate of the header
+ * @param header_y The y coordinate of the header
+ * @param text The text of the dialog
+ * @param text_x The x coordinate of the dialog
+ * @param text_y The y coordinate of the dialog
+ * @param left_button_text The text of the left button
+ * @param right_button_text The text of the right button
+ * @param center_button_text The text of the center button
+ * @param result_callback The result callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the result callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_dialog_ex(
+    DialogEx **dialog_ex,
+    int32_t view_id,
+    char *header,
+    uint16_t header_x,
+    uint16_t header_y,
+    char *text,
+    uint16_t text_x,
+    uint16_t text_y,
+    char *left_button_text,
+    char *right_button_text,
+    char *center_button_text,
+    void (*result_callback)(DialogExResult, void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a Popup object
+ * @param popup The Popup object to initialize
+ * @param view_id The ID/Index of the view
+ * @param header The header of the dialog
+ * @param header_x The x coordinate of the header
+ * @param header_y The y coordinate of the header
+ * @param text The text of the dialog
+ * @param text_x The x coordinate of the dialog
+ * @param text_y The y coordinate of the dialog
+ * @param result_callback The result callback function
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @param context The context to pass to the result callback
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_popup(
+    Popup **popup,
+    int32_t view_id,
+    char *header,
+    uint16_t header_x,
+    uint16_t header_y,
+    char *text,
+    uint16_t text_x,
+    uint16_t text_y,
+    void (*result_callback)(void *),
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher,
+    void *context);
+
+/**
+ * @brief Initialize a Loading object
+ * @param loading The Loading object to initialize
+ * @param view_id The ID/Index of the view
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_loading(
+    Loading **loading,
+    int32_t view_id,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher);
+
+/**
+ * @brief Set a char butter to a FuriString
+ * @param furi_string The FuriString object
+ * @param buffer The buffer to copy the string to
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_char_to_furi_string(FuriString **furi_string, char *buffer);
+
+/**
+ * @brief Initialize a TextBox object
+ * @param text_box The TextBox object to initialize
+ * @param view_id The ID/Index of the view
+ * @param text The text to display in the text box
+ * @param start_at_end Start the text box at the end
+ * @param previous_callback The previous callback function (can be set to NULL)
+ * @param view_dispatcher The ViewDispatcher object
+ * @return true if successful, false otherwise
+ */
+bool easy_flipper_set_text_box(
+    TextBox **text_box,
+    int32_t view_id,
+    char *text,
+    bool start_at_end,
+    uint32_t(previous_callback)(void *),
+    ViewDispatcher **view_dispatcher);
+
+#endif

+ 674 - 0
flip_world/engine/LICENSE

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program 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.
+
+    This program 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 <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 28 - 0
flip_world/engine/canvas.c

@@ -0,0 +1,28 @@
+#include <furi.h>
+#include "canvas.h"
+
+void canvas_printf(Canvas* canvas, uint8_t x, uint8_t y, const char* format, ...) {
+    FuriString* string = furi_string_alloc();
+    va_list args;
+    va_start(args, format);
+    furi_string_vprintf(string, format, args);
+    va_end(args);
+
+    canvas_draw_str(canvas, x, y, furi_string_get_cstr(string));
+
+    furi_string_free(string);
+}
+
+size_t canvas_printf_width(Canvas* canvas, const char* format, ...) {
+    FuriString* string = furi_string_alloc();
+    va_list args;
+    va_start(args, format);
+    furi_string_vprintf(string, format, args);
+    va_end(args);
+
+    size_t size = canvas_string_width(canvas, furi_string_get_cstr(string));
+
+    furi_string_free(string);
+
+    return size;
+}

+ 32 - 0
flip_world/engine/canvas.h

@@ -0,0 +1,32 @@
+#pragma once
+#include <stddef.h>
+#include <gui/canvas.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief Print formatted string to canvas
+ * 
+ * @param canvas canvas instance
+ * @param x x position
+ * @param y y position
+ * @param format format string
+ * @param ...  arguments
+ */
+void canvas_printf(Canvas* canvas, uint8_t x, uint8_t y, const char* format, ...);
+
+/**
+ * @brief Get width of formatted string
+ * 
+ * @param canvas canvas instance
+ * @param format format string
+ * @param ... arguments
+ * @return size_t width of formatted string
+ */
+size_t canvas_printf_width(Canvas* canvas, const char* format, ...);
+
+#ifdef __cplusplus
+}
+#endif

+ 53 - 0
flip_world/engine/clock_timer.c

@@ -0,0 +1,53 @@
+#include "clock_timer.h"
+#include <stdlib.h>
+
+#include <furi_hal_interrupt.h>
+#include <furi_hal_bus.h>
+#include <stm32wbxx_ll_tim.h>
+
+#define FURI_HAL_CLOCK_TIMER TIM2
+#define FURI_HAL_CLOCK_TIMER_BUS FuriHalBusTIM2
+#define FURI_HAL_CLOCK_TIMER_IRQ FuriHalInterruptIdTIM2
+
+typedef struct {
+    ClockTimerCallback callback;
+    void* context;
+} ClockTimer;
+
+static ClockTimer clock_timer = {
+    .callback = NULL,
+    .context = NULL,
+};
+
+static void clock_timer_isr(void* context) {
+    if(clock_timer.callback) {
+        clock_timer.callback(context);
+    }
+
+    LL_TIM_ClearFlag_UPDATE(FURI_HAL_CLOCK_TIMER);
+}
+
+void clock_timer_start(ClockTimerCallback callback, void* context, float period) {
+    clock_timer.callback = callback;
+    clock_timer.context = context;
+
+    furi_hal_bus_enable(FURI_HAL_CLOCK_TIMER_BUS);
+
+    // init timer to produce interrupts
+    LL_TIM_InitTypeDef TIM_InitStruct = {0};
+    TIM_InitStruct.Autoreload = (SystemCoreClock / period) - 1;
+    LL_TIM_Init(FURI_HAL_CLOCK_TIMER, &TIM_InitStruct);
+
+    furi_hal_interrupt_set_isr(FURI_HAL_CLOCK_TIMER_IRQ, clock_timer_isr, clock_timer.context);
+
+    LL_TIM_EnableIT_UPDATE(FURI_HAL_CLOCK_TIMER);
+    LL_TIM_EnableCounter(FURI_HAL_CLOCK_TIMER);
+}
+
+void clock_timer_stop(void) {
+    LL_TIM_DisableIT_UPDATE(FURI_HAL_CLOCK_TIMER);
+    LL_TIM_DisableCounter(FURI_HAL_CLOCK_TIMER);
+
+    furi_hal_bus_disable(FURI_HAL_CLOCK_TIMER_BUS);
+    furi_hal_interrupt_set_isr(FURI_HAL_CLOCK_TIMER_IRQ, NULL, NULL);
+}

+ 15 - 0
flip_world/engine/clock_timer.h

@@ -0,0 +1,15 @@
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void (*ClockTimerCallback)(void* context);
+
+void clock_timer_start(ClockTimerCallback callback, void* context, float period);
+
+void clock_timer_stop(void);
+
+#ifdef __cplusplus
+}
+#endif

+ 27 - 0
flip_world/engine/engine.h

@@ -0,0 +1,27 @@
+#pragma once
+#include <furi.h>
+#include "game_engine.h"
+#include "level.h"
+#include "entity.h"
+#include "game_manager.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    typedef struct
+    {
+        float target_fps;
+        bool show_fps;
+        bool always_backlight;
+        void (*start)(GameManager *game_manager, void *context);
+        void (*stop)(void *context);
+        size_t context_size;
+    } Game;
+
+    extern const Game game;
+
+#ifdef __cplusplus
+}
+#endif

+ 217 - 0
flip_world/engine/entity.c

@@ -0,0 +1,217 @@
+#include "entity.h"
+#include "entity_i.h"
+#include <stdlib.h>
+#include <furi.h>
+
+#ifdef ENTITY_DEBUG
+#define ENTITY_D(...) FURI_LOG_D("Entity", __VA_ARGS__)
+#else
+#define ENTITY_D(...)
+#endif
+
+static int32_t entities_count = 0;
+
+int32_t entities_get_count(void) {
+    return entities_count;
+}
+
+Entity* entity_alloc(const EntityDescription* description) {
+    entities_count++;
+    Entity* entity = malloc(sizeof(Entity));
+    entity->position = VECTOR_ZERO;
+    entity->description = description;
+    entity->context = NULL;
+    if(description && description->context_size > 0) {
+        entity->context = malloc(description->context_size);
+    }
+    entity->collider = NULL;
+    entity->collider_offset = VECTOR_ZERO;
+    ENTITY_D("Allocated at %p", entity);
+    entity->collider_dirty = false;
+    return entity;
+}
+
+void entity_collider_add_circle(Entity* entity, float radius) {
+    furi_check(entity->collider == NULL, "Collider already added");
+    entity->collider = malloc(sizeof(Collider));
+    entity->collider->type = ColliderTypeCircle;
+    entity->collider->circle.radius = radius;
+    entity->collider_dirty = true;
+}
+
+void entity_collider_add_rect(Entity* entity, float width, float height) {
+    furi_check(entity->collider == NULL, "Collider already added");
+    entity->collider = malloc(sizeof(Collider));
+    entity->collider->type = ColliderTypeRect;
+    entity->collider->rect.half_width = width / 2;
+    entity->collider->rect.half_height = height / 2;
+    entity->collider_dirty = true;
+}
+
+void entity_collider_remove(Entity* entity) {
+    furi_check(entity->collider != NULL, "Collider not added");
+    free(entity->collider);
+    entity->collider = NULL;
+    entity->collider_dirty = false;
+}
+
+void entity_collider_offset_set(Entity* entity, Vector offset) {
+    entity->collider_offset = offset;
+    entity->collider_dirty = true;
+}
+
+Vector entity_collider_offset_get(Entity* entity) {
+    return entity->collider_offset;
+}
+
+static Vector entity_collider_position_get(Entity* entity) {
+    return (Vector){
+        .x = entity->position.x + entity->collider_offset.x,
+        .y = entity->position.y + entity->collider_offset.y,
+    };
+}
+
+void entity_free(Entity* entity) {
+    entities_count--;
+    ENTITY_D("Freeing at %p", entity);
+    if(entity->context) {
+        free(entity->context);
+    }
+    if(entity->collider) {
+        free(entity->collider);
+    }
+    free(entity);
+}
+
+const EntityDescription* entity_description_get(Entity* entity) {
+    return entity->description;
+}
+
+Vector entity_pos_get(Entity* entity) {
+    return entity->position;
+}
+
+void entity_pos_set(Entity* entity, Vector position) {
+    entity->position = position;
+    entity->collider_dirty = true;
+}
+
+void* entity_context_get(Entity* entity) {
+    return entity->context;
+}
+
+void entity_call_start(Entity* entity, GameManager* manager) {
+    if(entity->description && entity->description->start) {
+        entity->description->start(entity, manager, entity->context);
+    }
+}
+
+void entity_call_stop(Entity* entity, GameManager* manager) {
+    if(entity->description && entity->description->stop) {
+        entity->description->stop(entity, manager, entity->context);
+    }
+}
+
+void entity_call_update(Entity* entity, GameManager* manager) {
+    if(entity->description && entity->description->update) {
+        entity->description->update(entity, manager, entity->context);
+    }
+}
+
+void entity_call_render(Entity* entity, GameManager* manager, Canvas* canvas) {
+    if(entity->description && entity->description->render) {
+        entity->description->render(entity, manager, canvas, entity->context);
+    }
+}
+
+void entity_call_collision(Entity* entity, Entity* other, GameManager* manager) {
+    if(entity->description && entity->description->collision) {
+        entity->description->collision(entity, other, manager, entity->context);
+    }
+}
+
+bool entity_collider_circle_circle(Entity* entity, Entity* other) {
+    Vector pos1 = entity_collider_position_get(entity);
+    Vector pos2 = entity_collider_position_get(other);
+
+    float dx = pos1.x - pos2.x;
+    float dy = pos1.y - pos2.y;
+    float distance = sqrtf(dx * dx + dy * dy);
+    return distance < entity->collider->circle.radius + other->collider->circle.radius;
+}
+
+bool entity_collider_rect_rect(Entity* entity, Entity* other) {
+    Vector pos1 = entity_collider_position_get(entity);
+    Vector pos2 = entity_collider_position_get(other);
+
+    float left1 = pos1.x - entity->collider->rect.half_width;
+    float right1 = pos1.x + entity->collider->rect.half_width;
+    float top1 = pos1.y - entity->collider->rect.half_height;
+    float bottom1 = pos1.y + entity->collider->rect.half_height;
+
+    float left2 = pos2.x - other->collider->rect.half_width;
+    float right2 = pos2.x + other->collider->rect.half_width;
+    float top2 = pos2.y - other->collider->rect.half_height;
+    float bottom2 = pos2.y + other->collider->rect.half_height;
+
+    return left1 < right2 && right1 > left2 && top1 < bottom2 && bottom1 > top2;
+}
+
+bool entity_collider_circle_rect(Entity* circle, Entity* rect) {
+    Vector pos1 = entity_collider_position_get(circle);
+    Vector pos2 = entity_collider_position_get(rect);
+
+    float left = pos2.x - rect->collider->rect.half_width;
+    float right = pos2.x + rect->collider->rect.half_width;
+    float top = pos2.y - rect->collider->rect.half_height;
+    float bottom = pos2.y + rect->collider->rect.half_height;
+
+    float closestX = fmaxf(left, fminf(pos1.x, right));
+    float closestY = fmaxf(top, fminf(pos1.y, bottom));
+
+    float dx = pos1.x - closestX;
+    float dy = pos1.y - closestY;
+    float distance = sqrtf(dx * dx + dy * dy);
+    return distance < circle->collider->circle.radius;
+}
+
+bool entity_collider_check_collision(Entity* entity, Entity* other) {
+    furi_check(entity->collider);
+    furi_check(other->collider);
+
+    if(entity->collider->type == ColliderTypeCircle) {
+        Entity* circle = entity;
+        if(other->collider->type == ColliderTypeCircle) {
+            return entity_collider_circle_circle(circle, other);
+        } else {
+            return entity_collider_circle_rect(circle, other);
+        }
+    } else {
+        Entity* rect = entity;
+        if(other->collider->type == ColliderTypeCircle) {
+            return entity_collider_circle_rect(other, rect);
+        } else {
+            return entity_collider_rect_rect(rect, other);
+        }
+    }
+}
+
+bool entity_collider_exists(Entity* entity) {
+    return entity->collider != NULL;
+}
+
+void entity_send_event(
+    Entity* sender,
+    Entity* receiver,
+    GameManager* manager,
+    uint32_t type,
+    EntityEventValue value) {
+    if(receiver->description && receiver->description->event) {
+        EntityEvent event = {
+            .type = type,
+            .sender = sender,
+            .value = value,
+        };
+        receiver->description->event(receiver, manager, event, receiver->context);
+    }
+}

+ 65 - 0
flip_world/engine/entity.h

@@ -0,0 +1,65 @@
+#pragma once
+#include "vector.h"
+#include "game_engine.h"
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct Entity Entity;
+
+typedef struct Level Level;
+
+typedef union {
+    uint32_t value;
+    void* pointer;
+} EntityEventValue;
+
+typedef struct {
+    uint32_t type;
+    Entity* sender;
+    EntityEventValue value;
+} EntityEvent;
+
+typedef struct Level Level;
+typedef struct GameManager GameManager;
+
+typedef struct {
+    void (*start)(Entity* self, GameManager* manager, void* context);
+    void (*stop)(Entity* self, GameManager* manager, void* context);
+    void (*update)(Entity* self, GameManager* manager, void* context);
+    void (*render)(Entity* self, GameManager* manager, Canvas* canvas, void* context);
+    void (*collision)(Entity* self, Entity* other, GameManager* manager, void* context);
+    void (*event)(Entity* self, GameManager* manager, EntityEvent event, void* context);
+    size_t context_size;
+} EntityDescription;
+
+const EntityDescription* entity_description_get(Entity* entity);
+
+Vector entity_pos_get(Entity* entity);
+
+void entity_pos_set(Entity* entity, Vector position);
+
+void* entity_context_get(Entity* entity);
+
+void entity_collider_add_circle(Entity* entity, float radius);
+
+void entity_collider_add_rect(Entity* entity, float width, float height);
+
+void entity_collider_remove(Entity* entity);
+
+void entity_collider_offset_set(Entity* entity, Vector offset);
+
+Vector entity_collider_offset_get(Entity* entity);
+
+void entity_send_event(
+    Entity* sender,
+    Entity* receiver,
+    GameManager* manager,
+    uint32_t type,
+    EntityEventValue value);
+
+#ifdef __cplusplus
+}
+#endif

+ 58 - 0
flip_world/engine/entity_i.h

@@ -0,0 +1,58 @@
+#pragma once
+#include "entity.h"
+#include "game_manager.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    ColliderTypeCircle,
+    ColliderTypeRect,
+} ColliderType;
+
+typedef struct {
+    ColliderType type;
+    union {
+        struct {
+            float radius;
+        } circle;
+        struct {
+            float half_width;
+            float half_height;
+        } rect;
+    };
+} Collider;
+
+struct Entity {
+    Vector position;
+    const EntityDescription* description;
+    void* context;
+    Collider* collider;
+    Vector collider_offset;
+    bool collider_dirty;
+};
+
+Entity* entity_alloc(const EntityDescription* behaviour);
+
+void entity_free(Entity* entity);
+
+void entity_call_start(Entity* entity, GameManager* manager);
+
+void entity_call_stop(Entity* entity, GameManager* manager);
+
+void entity_call_update(Entity* entity, GameManager* manager);
+
+void entity_call_render(Entity* entity, GameManager* manager, Canvas* canvas);
+
+void entity_call_collision(Entity* entity, Entity* other, GameManager* manager);
+
+bool entity_collider_check_collision(Entity* entity, Entity* other);
+
+bool entity_collider_exists(Entity* entity);
+
+int32_t entities_get_count(void);
+
+#ifdef __cplusplus
+}
+#endif

+ 199 - 0
flip_world/engine/game_engine.c

@@ -0,0 +1,199 @@
+#include "game_engine.h"
+#include <furi.h>
+#include <gui/gui.h>
+#include <input/input.h>
+#include <notification/notification_messages.h>
+#include "clock_timer.h"
+
+typedef _Atomic uint32_t AtomicUint32;
+
+GameEngineSettings game_engine_settings_init() {
+    GameEngineSettings settings;
+    settings.target_fps = 30.0f;
+    settings.show_fps = false;
+    settings.always_backlight = true;
+    settings.start_callback = NULL;
+    settings.frame_callback = NULL;
+    settings.stop_callback = NULL;
+    settings.context = NULL;
+    return settings;
+}
+
+struct GameEngine {
+    Gui* gui;
+    NotificationApp* notifications;
+    FuriPubSub* input_pubsub;
+    FuriThreadId thread_id;
+    GameEngineSettings settings;
+    float fps;
+};
+
+typedef enum {
+    GameThreadFlagUpdate = 1 << 0,
+    GameThreadFlagStop = 1 << 1,
+} GameThreadFlag;
+
+#define GameThreadFlagMask (GameThreadFlagUpdate | GameThreadFlagStop)
+
+GameEngine* game_engine_alloc(GameEngineSettings settings) {
+    furi_check(settings.frame_callback != NULL);
+
+    GameEngine* engine = malloc(sizeof(GameEngine));
+    engine->gui = furi_record_open(RECORD_GUI);
+    engine->notifications = furi_record_open(RECORD_NOTIFICATION);
+    engine->input_pubsub = furi_record_open(RECORD_INPUT_EVENTS);
+    engine->thread_id = furi_thread_get_current_id();
+    engine->settings = settings;
+    engine->fps = 1.0f;
+
+    return engine;
+}
+
+void game_engine_free(GameEngine* engine) {
+    furi_record_close(RECORD_GUI);
+    furi_record_close(RECORD_NOTIFICATION);
+    furi_record_close(RECORD_INPUT_EVENTS);
+    free(engine);
+}
+
+static void clock_timer_callback(void* context) {
+    GameEngine* engine = context;
+    furi_thread_flags_set(engine->thread_id, GameThreadFlagUpdate);
+}
+
+static const GameKey keys[] = {
+    [InputKeyUp] = GameKeyUp,
+    [InputKeyDown] = GameKeyDown,
+    [InputKeyRight] = GameKeyRight,
+    [InputKeyLeft] = GameKeyLeft,
+    [InputKeyOk] = GameKeyOk,
+    [InputKeyBack] = GameKeyBack,
+};
+
+static const size_t keys_count = sizeof(keys) / sizeof(keys[0]);
+
+static void input_events_callback(const void* value, void* context) {
+    AtomicUint32* input_state = context;
+    const InputEvent* event = value;
+
+    if(event->key < keys_count) {
+        switch(event->type) {
+        case InputTypePress:
+            *input_state |= (keys[event->key]);
+            break;
+        case InputTypeRelease:
+            *input_state &= ~(keys[event->key]);
+            break;
+        default:
+            break;
+        }
+    }
+}
+
+void game_engine_run(GameEngine* engine) {
+    // input state
+    AtomicUint32 input_state = 0;
+    uint32_t input_prev_state = 0;
+
+    // set backlight if needed
+    if(engine->settings.always_backlight) {
+        notification_message(engine->notifications, &sequence_display_backlight_enforce_on);
+    }
+
+    // acquire gui canvas
+    Canvas* canvas = gui_direct_draw_acquire(engine->gui);
+
+    // subscribe to input events
+    FuriPubSubSubscription* input_subscription =
+        furi_pubsub_subscribe(engine->input_pubsub, input_events_callback, &input_state);
+
+    // call start callback, if any
+    if(engine->settings.start_callback) {
+        engine->settings.start_callback(engine, engine->settings.context);
+    }
+
+    // start "game update" timer
+    clock_timer_start(clock_timer_callback, engine, engine->settings.target_fps);
+
+    // init fps counter
+    uint32_t time_start = DWT->CYCCNT;
+
+    while(true) {
+        uint32_t flags =
+            furi_thread_flags_wait(GameThreadFlagMask, FuriFlagWaitAny, FuriWaitForever);
+        furi_check((flags & FuriFlagError) == 0);
+
+        if(flags & GameThreadFlagUpdate) {
+            // update fps counter
+            uint32_t time_end = DWT->CYCCNT;
+            uint32_t time_delta = time_end - time_start;
+            time_start = time_end;
+
+            // update input state
+            uint32_t input_current_state = input_state;
+            InputState input = {
+                .held = input_current_state,
+                .pressed = input_current_state & ~input_prev_state,
+                .released = ~input_current_state & input_prev_state,
+            };
+            input_prev_state = input_current_state;
+
+            // clear screen
+            canvas_reset(canvas);
+
+            // calculate actual fps
+            engine->fps = (float)SystemCoreClock / time_delta;
+
+            // do the work
+            engine->settings.frame_callback(engine, canvas, input, engine->settings.context);
+
+            // show fps if needed
+            if(engine->settings.show_fps) {
+                canvas_set_color(canvas, ColorXOR);
+                canvas_printf(canvas, 0, 7, "%u", (uint32_t)roundf(engine->fps));
+            }
+
+            // and output screen buffer
+            canvas_commit(canvas);
+
+            // throttle a bit
+            furi_delay_tick(2);
+        }
+
+        if(flags & GameThreadFlagStop) {
+            break;
+        }
+    }
+
+    // stop timer
+    clock_timer_stop();
+
+    // call stop callback, if any
+    if(engine->settings.stop_callback) {
+        engine->settings.stop_callback(engine, engine->settings.context);
+    }
+
+    // release gui canvas and unsubscribe from input events
+    gui_direct_draw_release(engine->gui);
+    furi_pubsub_unsubscribe(engine->input_pubsub, input_subscription);
+
+    if(engine->settings.always_backlight) {
+        notification_message(engine->notifications, &sequence_display_backlight_enforce_auto);
+    }
+}
+
+void game_engine_stop(GameEngine* engine) {
+    furi_thread_flags_set(engine->thread_id, GameThreadFlagStop);
+}
+
+float game_engine_get_delta_time(GameEngine* engine) {
+    return 1.0f / engine->fps;
+}
+
+float game_engine_get_delta_frames(GameEngine* engine) {
+    return engine->fps / engine->settings.target_fps;
+}
+
+void game_engine_show_fps_set(GameEngine* engine, bool show_fps) {
+    engine->settings.show_fps = show_fps;
+}

+ 88 - 0
flip_world/engine/game_engine.h

@@ -0,0 +1,88 @@
+#pragma once
+#include <stdbool.h>
+#include "canvas.h"
+#include <gui/canvas.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    GameKeyUp = 1 << 0,
+    GameKeyDown = 1 << 1,
+    GameKeyRight = 1 << 2,
+    GameKeyLeft = 1 << 3,
+    GameKeyOk = 1 << 4,
+    GameKeyBack = 1 << 5,
+} GameKey;
+
+typedef struct {
+    uint32_t held; // mask of GameKey held in current frame
+    uint32_t pressed; // mask of GameKey pressed in current frame
+    uint32_t released; // mask of GameKey released in current frame
+} InputState;
+
+typedef struct GameEngine GameEngine;
+
+typedef void (*GameEngineStartCallback)(GameEngine* engine, void* context);
+
+typedef void (*GameEngineStopCallback)(GameEngine* engine, void* context);
+
+typedef void (
+    *GameEngineFrameCallback)(GameEngine* engine, Canvas* canvas, InputState input, void* context);
+
+typedef struct {
+    float target_fps; // target fps
+    bool show_fps; // show fps counter
+    bool always_backlight; // keep backlight on
+    GameEngineStartCallback start_callback; // called when engine starts
+    GameEngineFrameCallback frame_callback; // frame callback, called at target fps
+    GameEngineStopCallback stop_callback; // called when engine stops
+    void* context; // user context passed to callback
+} GameEngineSettings;
+
+/** Default settings initializer */
+GameEngineSettings game_engine_settings_init(void);
+
+/** Game Engine allocator
+ * @param settings engine settings
+ * @return GameEngine*  GameEngine instance
+ */
+GameEngine* game_engine_alloc(GameEngineSettings settings);
+
+/** Run the Game Engine. Blocks until game_engine_stop() is called.
+ * @param engine GameEngine instance
+ */
+void game_engine_run(GameEngine* engine);
+
+/** Free the Game Engine
+ * @param engine GameEngine instance
+ */
+void game_engine_free(GameEngine* engine);
+
+/** Stop the Game Engine, will not block execution
+ * @param engine GameEngine instance
+ */
+void game_engine_stop(GameEngine* engine);
+
+/** Get delta time between current and previous frame
+ * @param engine GameEngine instance
+ * @return float  delta time in seconds
+ */
+float game_engine_get_delta_time(GameEngine* engine);
+
+/** Get delta frames between current and previous frame
+ * @param engine GameEngine instance
+ * @return float  delta frames
+ */
+float game_engine_get_delta_frames(GameEngine* engine);
+
+/** Enable/disable show fps counter
+ * @param engine GameEngine instance
+ * @param show_fps show fps counter
+ */
+void game_engine_show_fps_set(GameEngine* engine, bool show_fps);
+
+#ifdef __cplusplus
+}
+#endif

+ 162 - 0
flip_world/engine/game_manager.c

@@ -0,0 +1,162 @@
+#include "game_manager.h"
+#include "level_i.h"
+#include <furi.h>
+#include <m-list.h>
+#include <storage/storage.h>
+
+typedef struct {
+    Sprite* sprite;
+    FuriString* path;
+} SpriteCache;
+
+LIST_DEF(LevelList, Level*, M_POD_OPLIST);
+LIST_DEF(SpriteCacheList, SpriteCache, M_POD_OPLIST);
+
+struct GameManager {
+    LevelList_t levels;
+    Level* current_level;
+    Level* next_level;
+
+    GameEngine* engine;
+    InputState input;
+    void* game_context;
+
+    SpriteCacheList_t sprites;
+};
+
+GameManager* game_manager_alloc() {
+    GameManager* manager = malloc(sizeof(GameManager));
+    LevelList_init(manager->levels);
+    manager->current_level = NULL;
+    manager->next_level = NULL;
+    manager->engine = NULL;
+    manager->game_context = NULL;
+    memset(&manager->input, 0, sizeof(InputState));
+    SpriteCacheList_init(manager->sprites);
+    return manager;
+}
+
+void game_manager_free(GameManager* manager) {
+    level_call_stop(manager->current_level);
+
+    // Free all levels
+    {
+        LevelList_it_t it;
+        LevelList_it(it, manager->levels);
+        while(!LevelList_end_p(it)) {
+            level_call_free(*LevelList_cref(it));
+            level_free(*LevelList_cref(it));
+            LevelList_next(it);
+        }
+    }
+
+    LevelList_clear(manager->levels);
+
+    // Free all sprites
+    {
+        SpriteCacheList_it_t it;
+        SpriteCacheList_it(it, manager->sprites);
+        while(!SpriteCacheList_end_p(it)) {
+            furi_string_free(SpriteCacheList_cref(it)->path);
+            sprite_free(SpriteCacheList_cref(it)->sprite);
+            SpriteCacheList_next(it);
+        }
+    }
+    SpriteCacheList_clear(manager->sprites);
+    free(manager);
+}
+
+Level* game_manager_add_level(GameManager* manager, const LevelBehaviour* behaviour) {
+    UNUSED(manager);
+    Level* level = level_alloc(behaviour, manager);
+    LevelList_push_back(manager->levels, level);
+    level_call_alloc(level);
+    if(!manager->current_level) {
+        manager->current_level = level;
+        level_call_start(level);
+    }
+    return level;
+}
+
+void game_manager_next_level_set(GameManager* manager, Level* next_level) {
+    manager->next_level = next_level;
+}
+
+void game_manager_game_stop(GameManager* manager) {
+    GameEngine* engine = game_manager_engine_get(manager);
+    game_engine_stop(engine);
+}
+
+Level* game_manager_current_level_get(GameManager* manager) {
+    return manager->current_level;
+}
+
+void game_manager_update(GameManager* manager) {
+    if(manager->next_level) {
+        level_call_stop(manager->current_level);
+        manager->current_level = manager->next_level;
+        level_call_start(manager->current_level);
+        manager->next_level = NULL;
+    }
+
+    level_update(manager->current_level, manager);
+}
+
+void game_manager_render(GameManager* manager, Canvas* canvas) {
+    level_render(manager->current_level, manager, canvas);
+}
+
+void game_manager_engine_set(GameManager* manager, GameEngine* engine) {
+    manager->engine = engine;
+}
+
+void game_manager_input_set(GameManager* manager, InputState input) {
+    manager->input = input;
+}
+
+void game_manager_game_context_set(GameManager* manager, void* context) {
+    manager->game_context = context;
+}
+
+GameEngine* game_manager_engine_get(GameManager* manager) {
+    return manager->engine;
+}
+
+InputState game_manager_input_get(GameManager* manager) {
+    return manager->input;
+}
+
+void* game_manager_game_context_get(GameManager* manager) {
+    return manager->game_context;
+}
+
+void game_manager_show_fps_set(GameManager* manager, bool show_fps) {
+    GameEngine* engine = game_manager_engine_get(manager);
+    game_engine_show_fps_set(engine, show_fps);
+}
+
+Sprite* game_manager_sprite_load(GameManager* manager, const char* path) {
+    SpriteCacheList_it_t it;
+    SpriteCacheList_it(it, manager->sprites);
+    while(!SpriteCacheList_end_p(it)) {
+        if(furi_string_cmp(SpriteCacheList_cref(it)->path, path) == 0) {
+            return SpriteCacheList_cref(it)->sprite;
+        }
+        SpriteCacheList_next(it);
+    }
+
+    FuriString* path_full = furi_string_alloc_set(APP_ASSETS_PATH("sprites/"));
+    furi_string_cat(path_full, path);
+
+    Sprite* sprite = sprite_alloc(furi_string_get_cstr(path_full));
+    if(sprite) {
+        SpriteCache cache = {
+            .sprite = sprite,
+            .path = furi_string_alloc_set(path),
+        };
+        SpriteCacheList_push_back(manager->sprites, cache);
+    }
+    furi_string_free(path_full);
+
+    return sprite;
+}

+ 40 - 0
flip_world/engine/game_manager.h

@@ -0,0 +1,40 @@
+#pragma once
+#include "level.h"
+#include "game_engine.h"
+#include "sprite.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct GameManager GameManager;
+
+Level* game_manager_add_level(GameManager* manager, const LevelBehaviour* behaviour);
+
+void game_manager_next_level_set(GameManager* manager, Level* level);
+
+Level* game_manager_current_level_get(GameManager* manager);
+
+GameEngine* game_manager_engine_get(GameManager* manager);
+
+InputState game_manager_input_get(GameManager* manager);
+
+void* game_manager_game_context_get(GameManager* manager);
+
+void game_manager_game_stop(GameManager* manager);
+
+void game_manager_show_fps_set(GameManager* manager, bool show_fps);
+
+/**
+ * @brief Load a sprite from a file
+ * Sprite will be cached and reused if the same file is loaded again
+ * 
+ * @param manager game manager instance
+ * @param path sprite file path, relative to the game's assets folder
+ * @return Sprite* or NULL if the sprite could not be loaded
+ */
+Sprite* game_manager_sprite_load(GameManager* manager, const char* path);
+
+#ifdef __cplusplus
+}
+#endif

+ 24 - 0
flip_world/engine/game_manager_i.h

@@ -0,0 +1,24 @@
+#pragma once
+#include "game_manager.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+GameManager* game_manager_alloc(void);
+
+void game_manager_free(GameManager* manager);
+
+void game_manager_update(GameManager* manager);
+
+void game_manager_render(GameManager* manager, Canvas* canvas);
+
+void game_manager_engine_set(GameManager* manager, GameEngine* engine);
+
+void game_manager_input_set(GameManager* manager, InputState input);
+
+void game_manager_game_context_set(GameManager* manager, void* context);
+
+#ifdef __cplusplus
+}
+#endif

+ 214 - 0
flip_world/engine/level.c

@@ -0,0 +1,214 @@
+#include "level.h"
+#include "level_i.h"
+#include "entity_i.h"
+#include <m-list.h>
+#include <furi.h>
+
+LIST_DEF(EntityList, Entity*, M_POD_OPLIST);
+#define M_OPL_EntityList_t() LIST_OPLIST(EntityList)
+#define FOREACH(name, list) for \
+    M_EACH(name, list, EntityList_t)
+
+#define LEVEL_DEBUG(...) FURI_LOG_D("Level", __VA_ARGS__)
+#define LEVEL_ERROR(...) FURI_LOG_E("Level", __VA_ARGS__)
+
+struct Level {
+    EntityList_t entities;
+    EntityList_t to_add;
+    EntityList_t to_remove;
+    const LevelBehaviour* behaviour;
+    void* context;
+    GameManager* manager;
+};
+
+Level* level_alloc(const LevelBehaviour* behaviour, GameManager* manager) {
+    Level* level = malloc(sizeof(Level));
+    level->manager = manager;
+    EntityList_init(level->entities);
+    EntityList_init(level->to_add);
+    EntityList_init(level->to_remove);
+    level->behaviour = behaviour;
+    if(behaviour->context_size > 0) {
+        level->context = malloc(behaviour->context_size);
+    } else {
+        level->context = NULL;
+    }
+    LEVEL_DEBUG("Allocated level at %p", level);
+    return level;
+}
+
+static void level_process_add(Level* level) {
+    // move entities from to_add to entities
+    FOREACH(item, level->to_add) {
+        EntityList_push_back(level->entities, *item);
+    }
+    EntityList_clear(level->to_add);
+}
+
+static void level_process_remove(Level* level) {
+    // remove entities in to_remove from entities and free them
+    FOREACH(item, level->to_remove) {
+        entity_free(*item);
+        EntityList_it_t it;
+
+        // find and remove the entity from the entities list
+        for(EntityList_it(it, level->entities); !EntityList_end_p(it); EntityList_next(it)) {
+            if(*EntityList_ref(it) == *item) {
+                EntityList_remove(level->entities, it);
+                break;
+            }
+        }
+    }
+    EntityList_clear(level->to_remove);
+}
+
+static bool level_entity_in_list_p(EntityList_t list, Entity* entity) {
+    FOREACH(item, list) {
+        if(*item == entity) {
+            return true;
+        }
+    }
+    return false;
+}
+
+void level_free(Level* level) {
+    level_clear(level);
+
+    EntityList_clear(level->entities);
+    EntityList_clear(level->to_add);
+    EntityList_clear(level->to_remove);
+
+    if(level->behaviour->context_size > 0) {
+        free(level->context);
+    }
+
+    LEVEL_DEBUG("Freeing level at %p", level);
+    free(level);
+}
+
+void level_clear(Level* level) {
+    size_t iterations = 0;
+
+    do {
+        // process to_add and to_remove
+        level_process_add(level);
+        level_process_remove(level);
+
+        // remove entities from entities list
+        FOREACH(item, level->entities) {
+            if(!level_entity_in_list_p(level->to_remove, *item)) {
+                level_remove_entity(level, *item);
+            }
+        }
+
+        // check if we are looping too many times
+        iterations++;
+        if(iterations >= 100) {
+            LEVEL_ERROR("Level free looped too many times");
+        }
+
+        // entity_call_stop can call level_remove_entity or level_add_entity
+        // so we need to process to_add and to_remove again
+    } while(!EntityList_empty_p(level->to_add) || !EntityList_empty_p(level->to_remove));
+}
+
+Entity* level_add_entity(Level* level, const EntityDescription* description) {
+    Entity* entity = entity_alloc(description);
+    EntityList_push_back(level->to_add, entity);
+    entity_call_start(entity, level->manager);
+    return entity;
+}
+
+void level_remove_entity(Level* level, Entity* entity) {
+    EntityList_push_back(level->to_remove, entity);
+    entity_call_stop(entity, level->manager);
+}
+
+void level_send_event(
+    Level* level,
+    Entity* sender,
+    const EntityDescription* receiver_desc,
+    uint32_t type,
+    EntityEventValue value) {
+    FOREACH(item, level->entities) {
+        if(receiver_desc == entity_description_get(*item) || receiver_desc == NULL) {
+            entity_send_event(sender, *item, level->manager, type, value);
+        }
+    }
+}
+
+static void level_process_update(Level* level, GameManager* manager) {
+    FOREACH(item, level->entities) {
+        entity_call_update(*item, manager);
+    }
+}
+
+static void level_process_collision(Level* level, GameManager* manager) {
+    EntityList_it_t it_first;
+    EntityList_it_t it_second;
+
+    EntityList_it(it_first, level->entities);
+    while(!EntityList_end_p(it_first)) {
+        Entity* first = *EntityList_ref(it_first);
+        if(entity_collider_exists(first)) {
+            // start second iterator at the next entity,
+            // so we don't check the same pair twice
+            EntityList_it_set(it_second, it_first);
+            EntityList_next(it_second);
+            while(!EntityList_end_p(it_second)) {
+                Entity* second = *EntityList_ref(it_second);
+                if(first->collider_dirty || second->collider_dirty) {
+                    if(entity_collider_exists(second)) {
+                        if(entity_collider_check_collision(first, second)) {
+                            entity_call_collision(first, second, manager);
+                            entity_call_collision(second, first, manager);
+                        }
+                    }
+                }
+                EntityList_next(it_second);
+            }
+        }
+        EntityList_next(it_first);
+    }
+
+    FOREACH(item, level->entities) {
+        (*item)->collider_dirty = false;
+    }
+}
+
+void level_update(Level* level, GameManager* manager) {
+    level_process_add(level);
+    level_process_remove(level);
+    level_process_update(level, manager);
+    level_process_collision(level, manager);
+}
+
+void level_render(Level* level, GameManager* manager, Canvas* canvas) {
+    FOREACH(item, level->entities) {
+        entity_call_render(*item, manager, canvas);
+    }
+}
+
+void level_call_start(Level* level) {
+    if(level->behaviour->start) {
+        level->behaviour->start(level, level->manager, level->context);
+    }
+}
+
+void level_call_stop(Level* level) {
+    if(level->behaviour->stop) {
+        level->behaviour->stop(level, level->manager, level->context);
+    }
+}
+
+void level_call_alloc(Level* level) {
+    if(level->behaviour->alloc) {
+        level->behaviour->alloc(level, level->manager, level->context);
+    }
+}
+
+void level_call_free(Level* level) {
+    if(level->behaviour->free) {
+        level->behaviour->free(level, level->manager, level->context);
+    }
+}

+ 63 - 0
flip_world/engine/level.h

@@ -0,0 +1,63 @@
+#pragma once
+#include <stddef.h>
+#include "entity.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    typedef struct GameManager GameManager;
+
+    typedef struct
+    {
+        void (*alloc)(Level *level, GameManager *manager, void *context);
+        void (*free)(Level *level, GameManager *manager, void *context);
+        void (*start)(Level *level, GameManager *manager, void *context);
+        void (*stop)(Level *level, GameManager *manager, void *context);
+        size_t context_size;
+    } LevelBehaviour;
+
+    /**
+     * @brief Remove all entities from the level
+     *
+     * @param level level instance
+     */
+    void level_clear(Level *level);
+
+    /**
+     * @brief Add an entity to the level
+     *
+     * @param level level instance
+     * @param behaviour entity behaviour
+     * @return Entity*
+     */
+    Entity *level_add_entity(Level *level, const EntityDescription *behaviour);
+
+    /**
+     * @brief Remove an entity from the level
+     *
+     * @param level level instance
+     * @param entity entity to remove
+     */
+    void level_remove_entity(Level *level, Entity *entity);
+
+    /**
+     * @brief Send an event to all entities of a certain type in the level
+     *
+     * @param level level instance
+     * @param sender entity that sends the event
+     * @param receiver_desc entity description that will receive the event, NULL for all entities
+     * @param type event type
+     * @param value event value
+     */
+    void level_send_event(
+        Level *level,
+        Entity *sender,
+        const EntityDescription *receiver_desc,
+        uint32_t type,
+        EntityEventValue value);
+
+#ifdef __cplusplus
+}
+#endif

+ 26 - 0
flip_world/engine/level_i.h

@@ -0,0 +1,26 @@
+#pragma once
+#include "level.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+Level* level_alloc(const LevelBehaviour* behaviour, GameManager* manager);
+
+void level_free(Level* level);
+
+void level_update(Level* level, GameManager* manager);
+
+void level_render(Level* level, GameManager* manager, Canvas* canvas);
+
+void level_call_alloc(Level* level);
+
+void level_call_free(Level* level);
+
+void level_call_start(Level* level);
+
+void level_call_stop(Level* level);
+
+#ifdef __cplusplus
+}
+#endif

+ 59 - 0
flip_world/engine/main.c

@@ -0,0 +1,59 @@
+#include <furi.h>
+#include "engine.h"
+#include "game_engine.h"
+#include "game_manager_i.h"
+#include "level_i.h"
+#include "entity_i.h"
+
+// static void frame_cb(GameEngine *engine, Canvas *canvas, InputState input, void *context)
+// {
+//     UNUSED(engine);
+//     GameManager *game_manager = context;
+//     game_manager_input_set(game_manager, input);
+//     game_manager_update(game_manager);
+//     game_manager_render(game_manager, canvas);
+// }
+
+// int32_t game_app(void *p)
+// {
+//     UNUSED(p);
+//     GameManager *game_manager = game_manager_alloc();
+
+//     GameEngineSettings settings = game_engine_settings_init();
+//     settings.target_fps = game.target_fps;
+//     settings.show_fps = game.show_fps;
+//     settings.always_backlight = game.always_backlight;
+//     settings.frame_callback = frame_cb;
+//     settings.context = game_manager;
+
+//     GameEngine *engine = game_engine_alloc(settings);
+//     game_manager_engine_set(game_manager, engine);
+
+//     void *game_context = NULL;
+//     if (game.context_size > 0)
+//     {
+//         game_context = malloc(game.context_size);
+//         game_manager_game_context_set(game_manager, game_context);
+//     }
+//     game.start(game_manager, game_context);
+
+//     game_engine_run(engine);
+//     game_engine_free(engine);
+
+//     game_manager_free(game_manager);
+
+//     game.stop(game_context);
+//     if (game_context)
+//     {
+//         free(game_context);
+//     }
+
+//     int32_t entities = entities_get_count();
+//     if (entities != 0)
+//     {
+//         FURI_LOG_E("Game", "Memory leak detected: %ld entities still allocated", entities);
+//         return -1;
+//     }
+
+//     return 0;
+// }

+ 84 - 0
flip_world/engine/scripts/sprite_builder.py

@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+import argparse
+import io
+import logging
+import os
+import struct
+
+from PIL import Image, ImageOps
+
+# XBM flipper sprite (.fxbm) is 1-bit depth, width-padded to 8 bits
+# file format:
+#   uint32 size of the rest of the file in bytes
+#   uint32 width in px
+#   uint32 height in px
+#   uint8[] pixel data, every row is padded to 8 bits (like XBM)
+
+def image2xbm(input_file_path):
+    with Image.open(input_file_path) as im:
+        with io.BytesIO() as output:
+            bw = im.convert("1")
+            bw = ImageOps.invert(bw)
+            bw.save(output, format="XBM")
+            return output.getvalue()
+
+def xbm2fxbm(data):
+    # hell as it is, but it works
+    f = io.StringIO(data.decode().strip())
+    width = int(f.readline().strip().split(" ")[2])
+    height = int(f.readline().strip().split(" ")[2])
+    data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
+    data_str = data[1:-1].replace(",", " ").replace("0x", "")
+    image_bin = bytearray.fromhex(data_str)
+
+    output = struct.pack("<I", len(image_bin) + 8)
+    output += struct.pack("<II", width, height)
+    output += image_bin
+    return output
+
+def process_sprites(input_dir, output_dir):
+    for root, dirs, files in os.walk(input_dir):
+        for file in files:
+            if file.startswith('.'):
+                continue
+            
+            try:
+                input_file_path = os.path.join(root, file)
+                rel_path = os.path.relpath(input_file_path, input_dir)
+                new_rel_path = os.path.splitext(rel_path)[0] + ".fxbm"
+                output_file_path = os.path.join(output_dir, new_rel_path)
+
+                os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
+
+                print(f"Converting '{rel_path}' to '{new_rel_path}'")
+                xbm = image2xbm(input_file_path)
+                img_data = xbm2fxbm(xbm)
+                with open(output_file_path, "wb") as f:
+                    f.write(img_data)
+            except Exception as e:
+                print(f"Cannot convert '{rel_path}': {e}")
+
+def clear_directory(directory):
+    for root, dirs, files in os.walk(directory, topdown=False):
+        for name in files:
+            os.remove(os.path.join(root, name))
+        for name in dirs:
+            os.rmdir(os.path.join(root, name))
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("source", help="Source directory")
+    parser.add_argument("target", help="Target directory")
+    args = parser.parse_args()
+
+    logging.basicConfig(level=logging.ERROR)
+    logger = logging.getLogger(__name__)
+    logger.debug(f"Building sprites from {args.source} to {args.target}")
+
+    clear_directory(args.target)
+    process_sprites(args.source, args.target)
+
+    return 0
+
+if __name__ == "__main__":
+    main()

+ 297 - 0
flip_world/engine/sensors/ICM42688P/ICM42688P.c

@@ -0,0 +1,297 @@
+#include "ICM42688P_regs.h"
+#include "ICM42688P.h"
+
+#define TAG "ICM42688P"
+
+#define ICM42688P_TIMEOUT 100
+
+struct ICM42688P {
+    FuriHalSpiBusHandle* spi_bus;
+    const GpioPin* irq_pin;
+    float accel_scale;
+    float gyro_scale;
+};
+
+static const struct AccelFullScale {
+    float value;
+    uint8_t reg_mask;
+} accel_fs_modes[] = {
+    [AccelFullScale16G] = {16.f, ICM42688_AFS_16G},
+    [AccelFullScale8G] = {8.f, ICM42688_AFS_8G},
+    [AccelFullScale4G] = {4.f, ICM42688_AFS_4G},
+    [AccelFullScale2G] = {2.f, ICM42688_AFS_2G},
+};
+
+static const struct GyroFullScale {
+    float value;
+    uint8_t reg_mask;
+} gyro_fs_modes[] = {
+    [GyroFullScale2000DPS] = {2000.f, ICM42688_GFS_2000DPS},
+    [GyroFullScale1000DPS] = {1000.f, ICM42688_GFS_1000DPS},
+    [GyroFullScale500DPS] = {500.f, ICM42688_GFS_500DPS},
+    [GyroFullScale250DPS] = {250.f, ICM42688_GFS_250DPS},
+    [GyroFullScale125DPS] = {125.f, ICM42688_GFS_125DPS},
+    [GyroFullScale62_5DPS] = {62.5f, ICM42688_GFS_62_5DPS},
+    [GyroFullScale31_25DPS] = {31.25f, ICM42688_GFS_31_25DPS},
+    [GyroFullScale15_625DPS] = {15.625f, ICM42688_GFS_15_625DPS},
+};
+
+static bool icm42688p_write_reg(FuriHalSpiBusHandle* spi_bus, uint8_t addr, uint8_t value) {
+    bool res = false;
+    furi_hal_spi_acquire(spi_bus);
+    do {
+        uint8_t cmd_data[2] = {addr & 0x7F, value};
+        if(!furi_hal_spi_bus_tx(spi_bus, cmd_data, 2, ICM42688P_TIMEOUT)) break;
+        res = true;
+    } while(0);
+    furi_hal_spi_release(spi_bus);
+    return res;
+}
+
+static bool icm42688p_read_reg(FuriHalSpiBusHandle* spi_bus, uint8_t addr, uint8_t* value) {
+    bool res = false;
+    furi_hal_spi_acquire(spi_bus);
+    do {
+        uint8_t cmd_byte = addr | (1 << 7);
+        if(!furi_hal_spi_bus_tx(spi_bus, &cmd_byte, 1, ICM42688P_TIMEOUT)) break;
+        if(!furi_hal_spi_bus_rx(spi_bus, value, 1, ICM42688P_TIMEOUT)) break;
+        res = true;
+    } while(0);
+    furi_hal_spi_release(spi_bus);
+    return res;
+}
+
+static bool
+    icm42688p_read_mem(FuriHalSpiBusHandle* spi_bus, uint8_t addr, uint8_t* data, uint8_t len) {
+    bool res = false;
+    furi_hal_spi_acquire(spi_bus);
+    do {
+        uint8_t cmd_byte = addr | (1 << 7);
+        if(!furi_hal_spi_bus_tx(spi_bus, &cmd_byte, 1, ICM42688P_TIMEOUT)) break;
+        if(!furi_hal_spi_bus_rx(spi_bus, data, len, ICM42688P_TIMEOUT)) break;
+        res = true;
+    } while(0);
+    furi_hal_spi_release(spi_bus);
+    return res;
+}
+
+bool icm42688p_accel_config(
+    ICM42688P* icm42688p,
+    ICM42688PAccelFullScale full_scale,
+    ICM42688PDataRate rate) {
+    icm42688p->accel_scale = accel_fs_modes[full_scale].value;
+    uint8_t reg_value = accel_fs_modes[full_scale].reg_mask | rate;
+    return icm42688p_write_reg(icm42688p->spi_bus, ICM42688_ACCEL_CONFIG0, reg_value);
+}
+
+float icm42688p_accel_get_full_scale(ICM42688P* icm42688p) {
+    return icm42688p->accel_scale;
+}
+
+bool icm42688p_gyro_config(
+    ICM42688P* icm42688p,
+    ICM42688PGyroFullScale full_scale,
+    ICM42688PDataRate rate) {
+    icm42688p->gyro_scale = gyro_fs_modes[full_scale].value;
+    uint8_t reg_value = gyro_fs_modes[full_scale].reg_mask | rate;
+    return icm42688p_write_reg(icm42688p->spi_bus, ICM42688_GYRO_CONFIG0, reg_value);
+}
+
+float icm42688p_gyro_get_full_scale(ICM42688P* icm42688p) {
+    return icm42688p->gyro_scale;
+}
+
+bool icm42688p_read_accel_raw(ICM42688P* icm42688p, ICM42688PRawData* data) {
+    bool ret = icm42688p_read_mem(
+        icm42688p->spi_bus, ICM42688_ACCEL_DATA_X1, (uint8_t*)data, sizeof(ICM42688PRawData));
+    return ret;
+}
+
+bool icm42688p_read_gyro_raw(ICM42688P* icm42688p, ICM42688PRawData* data) {
+    bool ret = icm42688p_read_mem(
+        icm42688p->spi_bus, ICM42688_GYRO_DATA_X1, (uint8_t*)data, sizeof(ICM42688PRawData));
+    return ret;
+}
+
+bool icm42688p_write_gyro_offset(ICM42688P* icm42688p, ICM42688PScaledData* scaled_data) {
+    if((fabsf(scaled_data->x) > 64.f) || (fabsf(scaled_data->y) > 64.f) ||
+       (fabsf(scaled_data->z) > 64.f)) {
+        return false;
+    }
+
+    uint16_t offset_x = (uint16_t)(-(int16_t)(scaled_data->x * 32.f) * 16) >> 4;
+    uint16_t offset_y = (uint16_t)(-(int16_t)(scaled_data->y * 32.f) * 16) >> 4;
+    uint16_t offset_z = (uint16_t)(-(int16_t)(scaled_data->z * 32.f) * 16) >> 4;
+
+    uint8_t offset_regs[9];
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 4);
+    icm42688p_read_mem(icm42688p->spi_bus, ICM42688_OFFSET_USER0, offset_regs, 5);
+
+    offset_regs[0] = offset_x & 0xFF;
+    offset_regs[1] = (offset_x & 0xF00) >> 8;
+    offset_regs[1] |= (offset_y & 0xF00) >> 4;
+    offset_regs[2] = offset_y & 0xFF;
+    offset_regs[3] = offset_z & 0xFF;
+    offset_regs[4] &= 0xF0;
+    offset_regs[4] |= (offset_z & 0x0F00) >> 8;
+
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_OFFSET_USER0, offset_regs[0]);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_OFFSET_USER1, offset_regs[1]);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_OFFSET_USER2, offset_regs[2]);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_OFFSET_USER3, offset_regs[3]);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_OFFSET_USER4, offset_regs[4]);
+
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 0);
+    return true;
+}
+
+void icm42688p_apply_scale(ICM42688PRawData* raw_data, float full_scale, ICM42688PScaledData* data) {
+    data->x = ((float)(raw_data->x)) / 32768.f * full_scale;
+    data->y = ((float)(raw_data->y)) / 32768.f * full_scale;
+    data->z = ((float)(raw_data->z)) / 32768.f * full_scale;
+}
+
+void icm42688p_apply_scale_fifo(
+    ICM42688P* icm42688p,
+    ICM42688PFifoPacket* fifo_data,
+    ICM42688PScaledData* accel_data,
+    ICM42688PScaledData* gyro_data) {
+    float full_scale = icm42688p->accel_scale;
+    accel_data->x = ((float)(fifo_data->a_x)) / 32768.f * full_scale;
+    accel_data->y = ((float)(fifo_data->a_y)) / 32768.f * full_scale;
+    accel_data->z = ((float)(fifo_data->a_z)) / 32768.f * full_scale;
+
+    full_scale = icm42688p->gyro_scale;
+    gyro_data->x = ((float)(fifo_data->g_x)) / 32768.f * full_scale;
+    gyro_data->y = ((float)(fifo_data->g_y)) / 32768.f * full_scale;
+    gyro_data->z = ((float)(fifo_data->g_z)) / 32768.f * full_scale;
+}
+
+float icm42688p_read_temp(ICM42688P* icm42688p) {
+    uint8_t reg_val[2];
+
+    icm42688p_read_mem(icm42688p->spi_bus, ICM42688_TEMP_DATA1, reg_val, 2);
+    int16_t temp_int = (reg_val[0] << 8) | reg_val[1];
+    return ((float)temp_int / 132.48f) + 25.f;
+}
+
+void icm42688_fifo_enable(
+    ICM42688P* icm42688p,
+    ICM42688PIrqCallback irq_callback,
+    void* irq_context) {
+    // FIFO mode: stream
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_FIFO_CONFIG, (1 << 6));
+    // Little-endian data, FIFO count in records
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INTF_CONFIG0, (1 << 7) | (1 << 6));
+    // FIFO partial read, FIFO packet: gyro + accel TODO: 20bit
+    icm42688p_write_reg(
+        icm42688p->spi_bus, ICM42688_FIFO_CONFIG1, (1 << 6) | (1 << 5) | (1 << 1) | (1 << 0));
+    // FIFO irq watermark
+    uint16_t fifo_watermark = 1;
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_FIFO_CONFIG2, fifo_watermark & 0xFF);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_FIFO_CONFIG3, fifo_watermark >> 8);
+
+    // IRQ1: push-pull, active high
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_CONFIG, (1 << 1) | (1 << 0));
+    // Clear IRQ on status read
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_CONFIG0, 0);
+    // IRQ pulse duration
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_CONFIG1, (1 << 6) | (1 << 5));
+
+    uint8_t reg_data = 0;
+    icm42688p_read_reg(icm42688p->spi_bus, ICM42688_INT_STATUS, &reg_data);
+
+    furi_hal_gpio_init(icm42688p->irq_pin, GpioModeInterruptRise, GpioPullDown, GpioSpeedVeryHigh);
+    furi_hal_gpio_remove_int_callback(icm42688p->irq_pin);
+    furi_hal_gpio_add_int_callback(icm42688p->irq_pin, irq_callback, irq_context);
+
+    // IRQ1 source: FIFO threshold
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE0, (1 << 2));
+}
+
+void icm42688_fifo_disable(ICM42688P* icm42688p) {
+    furi_hal_gpio_remove_int_callback(icm42688p->irq_pin);
+    furi_hal_gpio_init(icm42688p->irq_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
+
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE0, 0);
+
+    // FIFO mode: bypass
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_FIFO_CONFIG, 0);
+}
+
+uint16_t icm42688_fifo_get_count(ICM42688P* icm42688p) {
+    uint16_t reg_val = 0;
+    icm42688p_read_mem(icm42688p->spi_bus, ICM42688_FIFO_COUNTH, (uint8_t*)&reg_val, 2);
+    return reg_val;
+}
+
+bool icm42688_fifo_read(ICM42688P* icm42688p, ICM42688PFifoPacket* data) {
+    icm42688p_read_mem(
+        icm42688p->spi_bus, ICM42688_FIFO_DATA, (uint8_t*)data, sizeof(ICM42688PFifoPacket));
+    return (data->header) & (1 << 7);
+}
+
+ICM42688P* icm42688p_alloc(FuriHalSpiBusHandle* spi_bus, const GpioPin* irq_pin) {
+    ICM42688P* icm42688p = malloc(sizeof(ICM42688P));
+    icm42688p->spi_bus = spi_bus;
+    icm42688p->irq_pin = irq_pin;
+    return icm42688p;
+}
+
+void icm42688p_free(ICM42688P* icm42688p) {
+    free(icm42688p);
+}
+
+bool icm42688p_init(ICM42688P* icm42688p) {
+    furi_hal_spi_bus_handle_init(icm42688p->spi_bus);
+
+    // Software reset
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 0); // Set reg bank to 0
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_DEVICE_CONFIG, 0x01); // SPI Mode 0, SW reset
+    furi_delay_ms(1);
+
+    uint8_t reg_value = 0;
+    bool read_ok = icm42688p_read_reg(icm42688p->spi_bus, ICM42688_WHO_AM_I, &reg_value);
+    if(!read_ok) {
+        FURI_LOG_E(TAG, "Chip ID read failed");
+        return false;
+    } else if(reg_value != ICM42688_WHOAMI) {
+        FURI_LOG_E(
+            TAG, "Sensor returned wrong ID 0x%02X, expected 0x%02X", reg_value, ICM42688_WHOAMI);
+        return false;
+    }
+
+    // Disable all interrupts
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE0, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE1, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE3, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE4, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 4);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE6, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INT_SOURCE7, 0);
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 0);
+
+    // Data format: little endian
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_INTF_CONFIG0, 0);
+
+    // Enable all sensors
+    icm42688p_write_reg(
+        icm42688p->spi_bus,
+        ICM42688_PWR_MGMT0,
+        ICM42688_PWR_TEMP_ON | ICM42688_PWR_GYRO_MODE_LN | ICM42688_PWR_ACCEL_MODE_LN);
+    furi_delay_ms(45);
+
+    icm42688p_accel_config(icm42688p, AccelFullScale16G, DataRate1kHz);
+    icm42688p_gyro_config(icm42688p, GyroFullScale2000DPS, DataRate1kHz);
+
+    return true;
+}
+
+bool icm42688p_deinit(ICM42688P* icm42688p) {
+    // Software reset
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_REG_BANK_SEL, 0); // Set reg bank to 0
+    icm42688p_write_reg(icm42688p->spi_bus, ICM42688_DEVICE_CONFIG, 0x01); // SPI Mode 0, SW reset
+
+    furi_hal_spi_bus_handle_deinit(icm42688p->spi_bus);
+    return true;
+}

+ 127 - 0
flip_world/engine/sensors/ICM42688P/ICM42688P.h

@@ -0,0 +1,127 @@
+#pragma once
+
+#include <furi.h>
+#include <furi_hal.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    DataRate32kHz = 0x01,
+    DataRate16kHz = 0x02,
+    DataRate8kHz = 0x03,
+    DataRate4kHz = 0x04,
+    DataRate2kHz = 0x05,
+    DataRate1kHz = 0x06,
+    DataRate200Hz = 0x07,
+    DataRate100Hz = 0x08,
+    DataRate50Hz = 0x09,
+    DataRate25Hz = 0x0A,
+    DataRate12_5Hz = 0x0B,
+    DataRate6_25Hz = 0x0C, // Accelerometer only
+    DataRate3_125Hz = 0x0D, // Accelerometer only
+    DataRate1_5625Hz = 0x0E, // Accelerometer only
+    DataRate500Hz = 0x0F,
+} ICM42688PDataRate;
+
+typedef enum {
+    AccelFullScale16G = 0,
+    AccelFullScale8G,
+    AccelFullScale4G,
+    AccelFullScale2G,
+    AccelFullScaleTotal,
+} ICM42688PAccelFullScale;
+
+typedef enum {
+    GyroFullScale2000DPS = 0,
+    GyroFullScale1000DPS,
+    GyroFullScale500DPS,
+    GyroFullScale250DPS,
+    GyroFullScale125DPS,
+    GyroFullScale62_5DPS,
+    GyroFullScale31_25DPS,
+    GyroFullScale15_625DPS,
+    GyroFullScaleTotal,
+} ICM42688PGyroFullScale;
+
+typedef struct {
+    int16_t x;
+    int16_t y;
+    int16_t z;
+} __attribute__((packed)) ICM42688PRawData;
+
+typedef struct {
+    uint8_t header;
+    int16_t a_x;
+    int16_t a_y;
+    int16_t a_z;
+    int16_t g_x;
+    int16_t g_y;
+    int16_t g_z;
+    uint8_t temp;
+    uint16_t ts;
+} __attribute__((packed)) ICM42688PFifoPacket;
+
+typedef struct {
+    float x;
+    float y;
+    float z;
+} ICM42688PScaledData;
+
+typedef struct ICM42688P ICM42688P;
+
+typedef void (*ICM42688PIrqCallback)(void* ctx);
+
+ICM42688P* icm42688p_alloc(FuriHalSpiBusHandle* spi_bus, const GpioPin* irq_pin);
+
+bool icm42688p_init(ICM42688P* icm42688p);
+
+bool icm42688p_deinit(ICM42688P* icm42688p);
+
+void icm42688p_free(ICM42688P* icm42688p);
+
+bool icm42688p_accel_config(
+    ICM42688P* icm42688p,
+    ICM42688PAccelFullScale full_scale,
+    ICM42688PDataRate rate);
+
+float icm42688p_accel_get_full_scale(ICM42688P* icm42688p);
+
+bool icm42688p_gyro_config(
+    ICM42688P* icm42688p,
+    ICM42688PGyroFullScale full_scale,
+    ICM42688PDataRate rate);
+
+float icm42688p_gyro_get_full_scale(ICM42688P* icm42688p);
+
+bool icm42688p_read_accel_raw(ICM42688P* icm42688p, ICM42688PRawData* data);
+
+bool icm42688p_read_gyro_raw(ICM42688P* icm42688p, ICM42688PRawData* data);
+
+bool icm42688p_write_gyro_offset(ICM42688P* icm42688p, ICM42688PScaledData* scaled_data);
+
+void icm42688p_apply_scale(ICM42688PRawData* raw_data, float full_scale, ICM42688PScaledData* data);
+
+void icm42688p_apply_scale_fifo(
+    ICM42688P* icm42688p,
+    ICM42688PFifoPacket* fifo_data,
+    ICM42688PScaledData* accel_data,
+    ICM42688PScaledData* gyro_data);
+
+float icm42688p_read_temp(ICM42688P* icm42688p);
+
+void icm42688_fifo_enable(
+    ICM42688P* icm42688p,
+    ICM42688PIrqCallback irq_callback,
+    void* irq_context);
+
+void icm42688_fifo_disable(ICM42688P* icm42688p);
+
+uint16_t icm42688_fifo_get_count(ICM42688P* icm42688p);
+
+bool icm42688_fifo_read(ICM42688P* icm42688p, ICM42688PFifoPacket* data);
+
+#ifdef __cplusplus
+}
+#endif

+ 176 - 0
flip_world/engine/sensors/ICM42688P/ICM42688P_regs.h

@@ -0,0 +1,176 @@
+#pragma once
+
+#define ICM42688_WHOAMI 0x47
+
+// Bank 0
+#define ICM42688_DEVICE_CONFIG 0x11
+#define ICM42688_DRIVE_CONFIG 0x13
+#define ICM42688_INT_CONFIG 0x14
+#define ICM42688_FIFO_CONFIG 0x16
+#define ICM42688_TEMP_DATA1 0x1D
+#define ICM42688_TEMP_DATA0 0x1E
+#define ICM42688_ACCEL_DATA_X1 0x1F
+#define ICM42688_ACCEL_DATA_X0 0x20
+#define ICM42688_ACCEL_DATA_Y1 0x21
+#define ICM42688_ACCEL_DATA_Y0 0x22
+#define ICM42688_ACCEL_DATA_Z1 0x23
+#define ICM42688_ACCEL_DATA_Z0 0x24
+#define ICM42688_GYRO_DATA_X1 0x25
+#define ICM42688_GYRO_DATA_X0 0x26
+#define ICM42688_GYRO_DATA_Y1 0x27
+#define ICM42688_GYRO_DATA_Y0 0x28
+#define ICM42688_GYRO_DATA_Z1 0x29
+#define ICM42688_GYRO_DATA_Z0 0x2A
+#define ICM42688_TMST_FSYNCH 0x2B
+#define ICM42688_TMST_FSYNCL 0x2C
+#define ICM42688_INT_STATUS 0x2D
+#define ICM42688_FIFO_COUNTH 0x2E
+#define ICM42688_FIFO_COUNTL 0x2F
+#define ICM42688_FIFO_DATA 0x30
+#define ICM42688_APEX_DATA0 0x31
+#define ICM42688_APEX_DATA1 0x32
+#define ICM42688_APEX_DATA2 0x33
+#define ICM42688_APEX_DATA3 0x34
+#define ICM42688_APEX_DATA4 0x35
+#define ICM42688_APEX_DATA5 0x36
+#define ICM42688_INT_STATUS2 0x37
+#define ICM42688_INT_STATUS3 0x38
+#define ICM42688_SIGNAL_PATH_RESET 0x4B
+#define ICM42688_INTF_CONFIG0 0x4C
+#define ICM42688_INTF_CONFIG1 0x4D
+#define ICM42688_PWR_MGMT0 0x4E
+#define ICM42688_GYRO_CONFIG0 0x4F
+#define ICM42688_ACCEL_CONFIG0 0x50
+#define ICM42688_GYRO_CONFIG1 0x51
+#define ICM42688_GYRO_ACCEL_CONFIG0 0x52
+#define ICM42688_ACCEL_CONFIG1 0x53
+#define ICM42688_TMST_CONFIG 0x54
+#define ICM42688_APEX_CONFIG0 0x56
+#define ICM42688_SMD_CONFIG 0x57
+#define ICM42688_FIFO_CONFIG1 0x5F
+#define ICM42688_FIFO_CONFIG2 0x60
+#define ICM42688_FIFO_CONFIG3 0x61
+#define ICM42688_FSYNC_CONFIG 0x62
+#define ICM42688_INT_CONFIG0 0x63
+#define ICM42688_INT_CONFIG1 0x64
+#define ICM42688_INT_SOURCE0 0x65
+#define ICM42688_INT_SOURCE1 0x66
+#define ICM42688_INT_SOURCE3 0x68
+#define ICM42688_INT_SOURCE4 0x69
+#define ICM42688_FIFO_LOST_PKT0 0x6C
+#define ICM42688_FIFO_LOST_PKT1 0x6D
+#define ICM42688_SELF_TEST_CONFIG 0x70
+#define ICM42688_WHO_AM_I 0x75
+#define ICM42688_REG_BANK_SEL 0x76
+
+// Bank 1
+#define ICM42688_SENSOR_CONFIG0 0x03
+#define ICM42688_GYRO_CONFIG_STATIC2 0x0B
+#define ICM42688_GYRO_CONFIG_STATIC3 0x0C
+#define ICM42688_GYRO_CONFIG_STATIC4 0x0D
+#define ICM42688_GYRO_CONFIG_STATIC5 0x0E
+#define ICM42688_GYRO_CONFIG_STATIC6 0x0F
+#define ICM42688_GYRO_CONFIG_STATIC7 0x10
+#define ICM42688_GYRO_CONFIG_STATIC8 0x11
+#define ICM42688_GYRO_CONFIG_STATIC9 0x12
+#define ICM42688_GYRO_CONFIG_STATIC10 0x13
+#define ICM42688_XG_ST_DATA 0x5F
+#define ICM42688_YG_ST_DATA 0x60
+#define ICM42688_ZG_ST_DATA 0x61
+#define ICM42688_TMSTVAL0 0x62
+#define ICM42688_TMSTVAL1 0x63
+#define ICM42688_TMSTVAL2 0x64
+#define ICM42688_INTF_CONFIG4 0x7A
+#define ICM42688_INTF_CONFIG5 0x7B
+#define ICM42688_INTF_CONFIG6 0x7C
+
+// Bank 2
+#define ICM42688_ACCEL_CONFIG_STATIC2 0x03
+#define ICM42688_ACCEL_CONFIG_STATIC3 0x04
+#define ICM42688_ACCEL_CONFIG_STATIC4 0x05
+#define ICM42688_XA_ST_DATA 0x3B
+#define ICM42688_YA_ST_DATA 0x3C
+#define ICM42688_ZA_ST_DATA 0x3D
+
+// Bank 4
+#define ICM42688_APEX_CONFIG1 0x40
+#define ICM42688_APEX_CONFIG2 0x41
+#define ICM42688_APEX_CONFIG3 0x42
+#define ICM42688_APEX_CONFIG4 0x43
+#define ICM42688_APEX_CONFIG5 0x44
+#define ICM42688_APEX_CONFIG6 0x45
+#define ICM42688_APEX_CONFIG7 0x46
+#define ICM42688_APEX_CONFIG8 0x47
+#define ICM42688_APEX_CONFIG9 0x48
+#define ICM42688_ACCEL_WOM_X_THR 0x4A
+#define ICM42688_ACCEL_WOM_Y_THR 0x4B
+#define ICM42688_ACCEL_WOM_Z_THR 0x4C
+#define ICM42688_INT_SOURCE6 0x4D
+#define ICM42688_INT_SOURCE7 0x4E
+#define ICM42688_INT_SOURCE8 0x4F
+#define ICM42688_INT_SOURCE9 0x50
+#define ICM42688_INT_SOURCE10 0x51
+#define ICM42688_OFFSET_USER0 0x77
+#define ICM42688_OFFSET_USER1 0x78
+#define ICM42688_OFFSET_USER2 0x79
+#define ICM42688_OFFSET_USER3 0x7A
+#define ICM42688_OFFSET_USER4 0x7B
+#define ICM42688_OFFSET_USER5 0x7C
+#define ICM42688_OFFSET_USER6 0x7D
+#define ICM42688_OFFSET_USER7 0x7E
+#define ICM42688_OFFSET_USER8 0x7F
+
+// PWR_MGMT0
+#define ICM42688_PWR_TEMP_ON (0 << 5)
+#define ICM42688_PWR_TEMP_OFF (1 << 5)
+#define ICM42688_PWR_IDLE (1 << 4)
+#define ICM42688_PWR_GYRO_MODE_OFF (0 << 2)
+#define ICM42688_PWR_GYRO_MODE_LN (3 << 2)
+#define ICM42688_PWR_ACCEL_MODE_OFF (0 << 0)
+#define ICM42688_PWR_ACCEL_MODE_LP (2 << 0)
+#define ICM42688_PWR_ACCEL_MODE_LN (3 << 0)
+
+// GYRO_CONFIG0
+#define ICM42688_GFS_2000DPS (0x00 << 5)
+#define ICM42688_GFS_1000DPS (0x01 << 5)
+#define ICM42688_GFS_500DPS (0x02 << 5)
+#define ICM42688_GFS_250DPS (0x03 << 5)
+#define ICM42688_GFS_125DPS (0x04 << 5)
+#define ICM42688_GFS_62_5DPS (0x05 << 5)
+#define ICM42688_GFS_31_25DPS (0x06 << 5)
+#define ICM42688_GFS_15_625DPS (0x07 << 5)
+
+#define ICM42688_GODR_32kHz 0x01
+#define ICM42688_GODR_16kHz 0x02
+#define ICM42688_GODR_8kHz 0x03
+#define ICM42688_GODR_4kHz 0x04
+#define ICM42688_GODR_2kHz 0x05
+#define ICM42688_GODR_1kHz 0x06
+#define ICM42688_GODR_200Hz 0x07
+#define ICM42688_GODR_100Hz 0x08
+#define ICM42688_GODR_50Hz 0x09
+#define ICM42688_GODR_25Hz 0x0A
+#define ICM42688_GODR_12_5Hz 0x0B
+#define ICM42688_GODR_500Hz 0x0F
+
+// ACCEL_CONFIG0
+#define ICM42688_AFS_16G (0x00 << 5)
+#define ICM42688_AFS_8G (0x01 << 5)
+#define ICM42688_AFS_4G (0x02 << 5)
+#define ICM42688_AFS_2G (0x03 << 5)
+
+#define ICM42688_AODR_32kHz 0x01
+#define ICM42688_AODR_16kHz 0x02
+#define ICM42688_AODR_8kHz 0x03
+#define ICM42688_AODR_4kHz 0x04
+#define ICM42688_AODR_2kHz 0x05
+#define ICM42688_AODR_1kHz 0x06
+#define ICM42688_AODR_200Hz 0x07
+#define ICM42688_AODR_100Hz 0x08
+#define ICM42688_AODR_50Hz 0x09
+#define ICM42688_AODR_25Hz 0x0A
+#define ICM42688_AODR_12_5Hz 0x0B
+#define ICM42688_AODR_6_25Hz 0x0C
+#define ICM42688_AODR_3_125Hz 0x0D
+#define ICM42688_AODR_1_5625Hz 0x0E
+#define ICM42688_AODR_500Hz 0x0F

+ 326 - 0
flip_world/engine/sensors/imu.c

@@ -0,0 +1,326 @@
+#include <furi.h>
+#include "imu.h"
+#include "ICM42688P/ICM42688P.h"
+
+#define TAG "IMU"
+
+#define ACCEL_GYRO_RATE DataRate100Hz
+
+#define FILTER_SAMPLE_FREQ 100.f
+#define FILTER_BETA 0.08f
+
+#define SAMPLE_RATE_DIV 5
+
+#define SENSITIVITY_K 30.f
+#define EXP_RATE 1.1f
+
+#define IMU_CALI_AVG 64
+
+typedef enum {
+    ImuStop = (1 << 0),
+    ImuNewData = (1 << 1),
+} ImuThreadFlags;
+
+#define FLAGS_ALL (ImuStop | ImuNewData)
+
+typedef struct {
+    float q0;
+    float q1;
+    float q2;
+    float q3;
+    float roll;
+    float pitch;
+    float yaw;
+} ImuProcessedData;
+
+typedef struct {
+    FuriThread* thread;
+    ICM42688P* icm42688p;
+    ImuProcessedData processed_data;
+} ImuThread;
+
+static void imu_madgwick_filter(
+    ImuProcessedData* out,
+    ICM42688PScaledData* accel,
+    ICM42688PScaledData* gyro);
+
+static void imu_irq_callback(void* context) {
+    furi_assert(context);
+    ImuThread* imu = context;
+    furi_thread_flags_set(furi_thread_get_id(imu->thread), ImuNewData);
+}
+
+static void imu_process_data(ImuThread* imu, ICM42688PFifoPacket* in_data) {
+    ICM42688PScaledData accel_data;
+    ICM42688PScaledData gyro_data;
+
+    // Get accel and gyro data in g and degrees/s
+    icm42688p_apply_scale_fifo(imu->icm42688p, in_data, &accel_data, &gyro_data);
+
+    // Gyro: degrees/s to rads/s
+    gyro_data.x = gyro_data.x / 180.f * M_PI;
+    gyro_data.y = gyro_data.y / 180.f * M_PI;
+    gyro_data.z = gyro_data.z / 180.f * M_PI;
+
+    // Sensor Fusion algorithm
+    ImuProcessedData* out = &imu->processed_data;
+    imu_madgwick_filter(out, &accel_data, &gyro_data);
+
+    // Quaternion to euler angles
+    float roll = atan2f(
+        out->q0 * out->q1 + out->q2 * out->q3, 0.5f - out->q1 * out->q1 - out->q2 * out->q2);
+    float pitch = asinf(-2.0f * (out->q1 * out->q3 - out->q0 * out->q2));
+    float yaw = atan2f(
+        out->q1 * out->q2 + out->q0 * out->q3, 0.5f - out->q2 * out->q2 - out->q3 * out->q3);
+
+    // Euler angles: rads to degrees
+    out->roll = roll / M_PI * 180.f;
+    out->pitch = pitch / M_PI * 180.f;
+    out->yaw = yaw / M_PI * 180.f;
+}
+
+static void calibrate_gyro(ImuThread* imu) {
+    ICM42688PRawData data;
+    ICM42688PScaledData offset_scaled = {.x = 0.f, .y = 0.f, .z = 0.f};
+
+    icm42688p_write_gyro_offset(imu->icm42688p, &offset_scaled);
+    furi_delay_ms(10);
+
+    int32_t avg_x = 0;
+    int32_t avg_y = 0;
+    int32_t avg_z = 0;
+
+    for(uint8_t i = 0; i < IMU_CALI_AVG; i++) {
+        icm42688p_read_gyro_raw(imu->icm42688p, &data);
+        avg_x += data.x;
+        avg_y += data.y;
+        avg_z += data.z;
+        furi_delay_ms(2);
+    }
+
+    data.x = avg_x / IMU_CALI_AVG;
+    data.y = avg_y / IMU_CALI_AVG;
+    data.z = avg_z / IMU_CALI_AVG;
+
+    icm42688p_apply_scale(&data, icm42688p_gyro_get_full_scale(imu->icm42688p), &offset_scaled);
+    FURI_LOG_I(
+        TAG,
+        "Offsets: x %f, y %f, z %f",
+        (double)offset_scaled.x,
+        (double)offset_scaled.y,
+        (double)offset_scaled.z);
+    icm42688p_write_gyro_offset(imu->icm42688p, &offset_scaled);
+}
+
+// static float imu_angle_diff(float a, float b) {
+//     float diff = a - b;
+//     if(diff > 180.f)
+//         diff -= 360.f;
+//     else if(diff < -180.f)
+//         diff += 360.f;
+
+//     return diff;
+// }
+
+static int32_t imu_thread(void* context) {
+    furi_assert(context);
+    ImuThread* imu = context;
+
+    // float yaw_last = 0.f;
+    // float pitch_last = 0.f;
+    // float diff_x = 0.f;
+    // float diff_y = 0.f;
+
+    calibrate_gyro(imu);
+
+    icm42688p_accel_config(imu->icm42688p, AccelFullScale16G, ACCEL_GYRO_RATE);
+    icm42688p_gyro_config(imu->icm42688p, GyroFullScale2000DPS, ACCEL_GYRO_RATE);
+
+    imu->processed_data.q0 = 1.f;
+    imu->processed_data.q1 = 0.f;
+    imu->processed_data.q2 = 0.f;
+    imu->processed_data.q3 = 0.f;
+    icm42688_fifo_enable(imu->icm42688p, imu_irq_callback, imu);
+
+    while(1) {
+        uint32_t events = furi_thread_flags_wait(FLAGS_ALL, FuriFlagWaitAny, FuriWaitForever);
+
+        if(events & ImuStop) {
+            break;
+        }
+
+        if(events & ImuNewData) {
+            uint16_t data_pending = icm42688_fifo_get_count(imu->icm42688p);
+            ICM42688PFifoPacket data;
+            while(data_pending--) {
+                icm42688_fifo_read(imu->icm42688p, &data);
+                imu_process_data(imu, &data);
+            }
+        }
+    }
+
+    icm42688_fifo_disable(imu->icm42688p);
+
+    return 0;
+}
+
+ImuThread* imu_start(ICM42688P* icm42688p) {
+    ImuThread* imu = malloc(sizeof(ImuThread));
+    imu->icm42688p = icm42688p;
+    imu->thread = furi_thread_alloc_ex("ImuThread", 4096, imu_thread, imu);
+
+    furi_thread_start(imu->thread);
+
+    return imu;
+}
+
+void imu_stop(ImuThread* imu) {
+    furi_assert(imu);
+
+    furi_thread_flags_set(furi_thread_get_id(imu->thread), ImuStop);
+
+    furi_thread_join(imu->thread);
+    furi_thread_free(imu->thread);
+
+    free(imu);
+}
+
+static float imu_inv_sqrt(float number) {
+    union {
+        float f;
+        uint32_t i;
+    } conv = {.f = number};
+    conv.i = 0x5F3759Df - (conv.i >> 1);
+    conv.f *= 1.5f - (number * 0.5f * conv.f * conv.f);
+    return conv.f;
+}
+
+/* Simple madgwik filter, based on: https://github.com/arduino-libraries/MadgwickAHRS/ */
+
+static void imu_madgwick_filter(
+    ImuProcessedData* out,
+    ICM42688PScaledData* accel,
+    ICM42688PScaledData* gyro) {
+    float recipNorm;
+    float s0, s1, s2, s3;
+    float qDot1, qDot2, qDot3, qDot4;
+    float _2q0, _2q1, _2q2, _2q3, _4q0, _4q1, _4q2, _8q1, _8q2, q0q0, q1q1, q2q2, q3q3;
+
+    // Rate of change of quaternion from gyroscope
+    qDot1 = 0.5f * (-out->q1 * gyro->x - out->q2 * gyro->y - out->q3 * gyro->z);
+    qDot2 = 0.5f * (out->q0 * gyro->x + out->q2 * gyro->z - out->q3 * gyro->y);
+    qDot3 = 0.5f * (out->q0 * gyro->y - out->q1 * gyro->z + out->q3 * gyro->x);
+    qDot4 = 0.5f * (out->q0 * gyro->z + out->q1 * gyro->y - out->q2 * gyro->x);
+
+    // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)
+    if(!((accel->x == 0.0f) && (accel->y == 0.0f) && (accel->z == 0.0f))) {
+        // Normalise accelerometer measurement
+        recipNorm = imu_inv_sqrt(accel->x * accel->x + accel->y * accel->y + accel->z * accel->z);
+        accel->x *= recipNorm;
+        accel->y *= recipNorm;
+        accel->z *= recipNorm;
+
+        // Auxiliary variables to avoid repeated arithmetic
+        _2q0 = 2.0f * out->q0;
+        _2q1 = 2.0f * out->q1;
+        _2q2 = 2.0f * out->q2;
+        _2q3 = 2.0f * out->q3;
+        _4q0 = 4.0f * out->q0;
+        _4q1 = 4.0f * out->q1;
+        _4q2 = 4.0f * out->q2;
+        _8q1 = 8.0f * out->q1;
+        _8q2 = 8.0f * out->q2;
+        q0q0 = out->q0 * out->q0;
+        q1q1 = out->q1 * out->q1;
+        q2q2 = out->q2 * out->q2;
+        q3q3 = out->q3 * out->q3;
+
+        // Gradient decent algorithm corrective step
+        s0 = _4q0 * q2q2 + _2q2 * accel->x + _4q0 * q1q1 - _2q1 * accel->y;
+        s1 = _4q1 * q3q3 - _2q3 * accel->x + 4.0f * q0q0 * out->q1 - _2q0 * accel->y - _4q1 +
+             _8q1 * q1q1 + _8q1 * q2q2 + _4q1 * accel->z;
+        s2 = 4.0f * q0q0 * out->q2 + _2q0 * accel->x + _4q2 * q3q3 - _2q3 * accel->y - _4q2 +
+             _8q2 * q1q1 + _8q2 * q2q2 + _4q2 * accel->z;
+        s3 = 4.0f * q1q1 * out->q3 - _2q1 * accel->x + 4.0f * q2q2 * out->q3 - _2q2 * accel->y;
+        recipNorm =
+            imu_inv_sqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude
+        s0 *= recipNorm;
+        s1 *= recipNorm;
+        s2 *= recipNorm;
+        s3 *= recipNorm;
+
+        // Apply feedback step
+        qDot1 -= FILTER_BETA * s0;
+        qDot2 -= FILTER_BETA * s1;
+        qDot3 -= FILTER_BETA * s2;
+        qDot4 -= FILTER_BETA * s3;
+    }
+
+    // Integrate rate of change of quaternion to yield quaternion
+    out->q0 += qDot1 * (1.0f / FILTER_SAMPLE_FREQ);
+    out->q1 += qDot2 * (1.0f / FILTER_SAMPLE_FREQ);
+    out->q2 += qDot3 * (1.0f / FILTER_SAMPLE_FREQ);
+    out->q3 += qDot4 * (1.0f / FILTER_SAMPLE_FREQ);
+
+    // Normalise quaternion
+    recipNorm = imu_inv_sqrt(
+        out->q0 * out->q0 + out->q1 * out->q1 + out->q2 * out->q2 + out->q3 * out->q3);
+    out->q0 *= recipNorm;
+    out->q1 *= recipNorm;
+    out->q2 *= recipNorm;
+    out->q3 *= recipNorm;
+}
+
+/* IMU API */
+
+struct Imu {
+    FuriHalSpiBusHandle* icm42688p_device;
+    ICM42688P* icm42688p;
+    ImuThread* thread;
+    bool present;
+};
+
+Imu* imu_alloc(void) {
+    Imu* imu = malloc(sizeof(Imu));
+    imu->icm42688p_device = malloc(sizeof(FuriHalSpiBusHandle));
+    memcpy(imu->icm42688p_device, &furi_hal_spi_bus_handle_external, sizeof(FuriHalSpiBusHandle));
+    imu->icm42688p_device->cs = &gpio_ext_pc3;
+
+    imu->icm42688p = icm42688p_alloc(imu->icm42688p_device, &gpio_ext_pb2);
+    imu->present = icm42688p_init(imu->icm42688p);
+
+    if(imu->present) {
+        imu->thread = imu_start(imu->icm42688p);
+    }
+
+    return imu;
+}
+
+void imu_free(Imu* imu) {
+    if(imu->present) {
+        imu_stop(imu->thread);
+    }
+    icm42688p_deinit(imu->icm42688p);
+    icm42688p_free(imu->icm42688p);
+    free(imu->icm42688p_device);
+    free(imu);
+}
+
+bool imu_present(Imu* imu) {
+    return imu->present;
+}
+
+float imu_pitch_get(Imu* imu) {
+    // we pretend that reading a float is an atomic operation
+    return imu->thread->processed_data.pitch;
+}
+
+float imu_roll_get(Imu* imu) {
+    // we pretend that reading a float is an atomic operation
+    return imu->thread->processed_data.roll;
+}
+
+float imu_yaw_get(Imu* imu) {
+    // we pretend that reading a float is an atomic operation
+    return imu->thread->processed_data.yaw;
+}

+ 15 - 0
flip_world/engine/sensors/imu.h

@@ -0,0 +1,15 @@
+#pragma once
+
+typedef struct Imu Imu;
+
+Imu* imu_alloc(void);
+
+void imu_free(Imu* imu);
+
+bool imu_present(Imu* imu);
+
+float imu_pitch_get(Imu* imu);
+
+float imu_roll_get(Imu* imu);
+
+float imu_yaw_get(Imu* imu);

+ 69 - 0
flip_world/engine/sprite.c

@@ -0,0 +1,69 @@
+#include "sprite.h"
+#include <storage/storage.h>
+
+#ifdef SPRITE_DEBUG
+#define SPRITE_D(...) FURI_LOG_D("Sprite", __VA_ARGS__)
+#define SPRITE_E(...) FURI_LOG_E("Sprite", __VA_ARGS__)
+#else
+#define SPRITE_D(...)
+#define SPRITE_E(...)
+#endif
+
+struct Sprite {
+    uint32_t width;
+    uint32_t height;
+    uint8_t data[];
+};
+
+Sprite* sprite_alloc(const char* path) {
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    File* file = storage_file_alloc(storage);
+    Sprite* sprite = NULL;
+
+    do {
+        if(!storage_file_open(file, path, FSAM_READ, FSOM_OPEN_EXISTING)) {
+            SPRITE_E("Failed to open file: %s", path);
+            break;
+        }
+
+        uint32_t size = 0;
+        if(storage_file_read(file, &size, sizeof(size)) != sizeof(size)) {
+            SPRITE_E("Failed to read file size: %s", path);
+            break;
+        }
+
+        sprite = malloc(size);
+        if(storage_file_read(file, sprite, size) != size) {
+            SPRITE_E("Failed to read file: %s", path);
+            free(sprite);
+            sprite = NULL;
+            break;
+        }
+
+        SPRITE_D(
+            "Loaded sprite: %s, width: %lu, height: %lu", path, sprite->width, sprite->height);
+    } while(false);
+
+    storage_file_free(file);
+
+    return sprite;
+}
+
+void sprite_free(Sprite* sprite) {
+    free(sprite);
+}
+
+size_t sprite_get_width(Sprite* sprite) {
+    return sprite->width;
+}
+
+size_t sprite_get_height(Sprite* sprite) {
+    return sprite->height;
+}
+
+void canvas_draw_sprite(Canvas* canvas, Sprite* sprite, int32_t x, int32_t y) {
+    furi_check(sprite->width);
+    furi_check(sprite->height);
+    furi_check(sprite->data);
+    canvas_draw_xbm(canvas, x, y, sprite->width, sprite->height, sprite->data);
+}

+ 44 - 0
flip_world/engine/sprite.h

@@ -0,0 +1,44 @@
+#pragma once
+#include <stdbool.h>
+#include <stddef.h>
+#include <gui/canvas.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct Sprite Sprite;
+
+/** Sprite allocator
+ * @return Sprite*  Sprite instance or NULL, if failed
+ */
+Sprite* sprite_alloc(const char* path);
+
+/** Sprite deallocator
+ * @param sprite Sprite instance
+ */
+void sprite_free(Sprite* sprite);
+
+/** Get sprite width
+ * @param sprite Sprite instance
+ * @return size_t sprite width
+ */
+size_t sprite_get_width(Sprite* sprite);
+
+/** Get sprite height
+ * @param sprite Sprite instance
+ * @return size_t sprite height
+ */
+size_t sprite_get_height(Sprite* sprite);
+
+/** Draw sprite on canvas
+ * @param canvas Canvas instance
+ * @param sprite Sprite instance
+ * @param x x coordinate
+ * @param y y coordinate
+ */
+void canvas_draw_sprite(Canvas* canvas, Sprite* sprite, int32_t x, int32_t y);
+
+#ifdef __cplusplus
+}
+#endif

+ 33 - 0
flip_world/engine/vector.c

@@ -0,0 +1,33 @@
+#include "vector.h"
+
+Vector vector_add(Vector a, Vector b) {
+    return (Vector){.x = a.x + b.x, .y = a.y + b.y};
+}
+
+Vector vector_sub(Vector a, Vector b) {
+    return (Vector){.x = a.x - b.x, .y = a.y - b.y};
+}
+
+Vector vector_mul(Vector a, Vector b) {
+    return (Vector){.x = a.x * b.x, .y = a.y * b.y};
+}
+
+Vector vector_div(Vector a, Vector b) {
+    return (Vector){.x = a.x / b.x, .y = a.y / b.y};
+}
+
+Vector vector_addf(Vector a, float b) {
+    return (Vector){.x = a.x + b, .y = a.y + b};
+}
+
+Vector vector_subf(Vector a, float b) {
+    return (Vector){.x = a.x - b, .y = a.y - b};
+}
+
+Vector vector_mulf(Vector a, float b) {
+    return (Vector){.x = a.x * b, .y = a.y * b};
+}
+
+Vector vector_divf(Vector a, float b) {
+    return (Vector){.x = a.x / b, .y = a.y / b};
+}

+ 32 - 0
flip_world/engine/vector.h

@@ -0,0 +1,32 @@
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+    float x;
+    float y;
+} Vector;
+
+#define VECTOR_ZERO ((Vector){0, 0})
+
+Vector vector_add(Vector a, Vector b);
+
+Vector vector_sub(Vector a, Vector b);
+
+Vector vector_mul(Vector a, Vector b);
+
+Vector vector_div(Vector a, Vector b);
+
+Vector vector_addf(Vector a, float b);
+
+Vector vector_subf(Vector a, float b);
+
+Vector vector_mulf(Vector a, float b);
+
+Vector vector_divf(Vector a, float b);
+
+#ifdef __cplusplus
+}
+#endif

BIN
flip_world/file_assets/sprites/enemy_left_cyclops_10x11px.fxbm


BIN
flip_world/file_assets/sprites/enemy_left_ghost_15x15px.fxbm


BIN
flip_world/file_assets/sprites/enemy_left_ogre_10x13px.fxbm


BIN
flip_world/file_assets/sprites/enemy_right_cyclops_10x11px.fxbm


BIN
flip_world/file_assets/sprites/enemy_right_ghost_15x15px.fxbm


BIN
flip_world/file_assets/sprites/enemy_right_ogre_10x13px.fxbm


BIN
flip_world/file_assets/sprites/npc_left_funny_15x21px.fxbm


BIN
flip_world/file_assets/sprites/npc_right_funny_15x21px.fxbm


BIN
flip_world/file_assets/sprites/player_left_axe_15x11px.fxbm


BIN
flip_world/file_assets/sprites/player_left_bow_13x11px.fxbm


BIN
flip_world/file_assets/sprites/player_left_naked_10x10px.fxbm


BIN
flip_world/file_assets/sprites/player_left_sword_15x11px.fxbm


BIN
flip_world/file_assets/sprites/player_right_axe_15x11px.fxbm


BIN
flip_world/file_assets/sprites/player_right_bow_13x11.fxbm


BIN
flip_world/file_assets/sprites/player_right_naked_10x10px.fxbm


BIN
flip_world/file_assets/sprites/player_right_sword_15x11px.fxbm


Vissa filer visades inte eftersom för många filer har ändrats