Installing Dear ImGui Library (OpenGL) for WebAssembly (Emscripten & CMake) Установка библиотеки Dear ImGui (OpenGL) для WebAssembly (Emscripten и CMake)
A step-by-step guide to downloading, extracting, and configuring the latest release of Dear ImGui with OpenGL (WebGL 2.0) in your CMake projects for WebAssembly on Windows using Emscripten. Пошаговое руководство по скачиванию, распаковке и настройке последней версии библиотеки Dear ImGui с OpenGL (WebGL 2.0) в проектах CMake для WebAssembly в Windows с использованием Emscripten.
Step 1: Download Source Code Шаг 1: Скачивание исходного кода
Check and download the latest release (such as v1.93.0) directly from the official Dear ImGui repository on GitHub:
Проверьте и скачайте последнюю версию (например, v1.93.0) напрямую со страницы релизов Dear ImGui на GitHub:
Open Dear ImGui Releases (GitHub) Открыть релизы Dear ImGui (GitHub) Download v1.93.0 (.zip) Скачать v1.93.0 (.zip)
Step 2: Extract the Library Шаг 2: Распаковка библиотеки
Unzip the downloaded archive so that the source files are located in C:\libs\imgui-1.93.0:
Распакуйте скачанный архив так, чтобы исходные файлы находились в папке C:\libs\imgui-1.93.0:
Step 3: Create Project Directory Шаг 3: Создание директории проекта
Create a workspace folder and a new directory for your ImGui WebAssembly test project: Создайте рабочую папку для проектов и новую директорию для вашего тестового WebAssembly-проекта ImGui:
Windows (Command Prompt / PowerShell)
mkdir C:\projects\imgui-opengl-web-test
cd C:\projects\imgui-opengl-web-test
Step 4: Create Source Files (main.cpp & CMakeLists.txt) Шаг 4: Создание исходных файлов (main.cpp и CMakeLists.txt)
Create the source files in your project directory using Notepad, VS Code, or Sublime Text: Создайте исходные файлы в папке проекта с помощью Блокнота, VS Code или Sublime Text:
Windows (Terminal / Notepad)
notepad main.cpp
notepad CMakeLists.txt
1. File Contents for main.cpp 1. Содержимое файла main.cpp
#include <iostream>
#include <GLES3/gl3.h>
#include <emscripten.h>
#include "imgui.h"
#include "imgui_impl_opengl3.h"
void loop() {
// Simulate ImGui frame lifecycle in the browser event loop
ImGui::NewFrame();
ImGui::Begin("OpenGL (WebGL 2.0) Test Window");
ImGui::Text("Hello, OpenGL (WebGL 2.0) with Dear ImGui!");
ImGui::End();
ImGui::Render();
}
int main(int argc, char** argv) {
// Initialize ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// Set virtual display size and frame delta time for headless execution verification
io.DisplaySize = ImVec2(1280.0f, 720.0f);
io.DeltaTime = 1.0f / 60.0f;
// Build font atlas explicitly when renderer backend isn't creating textures
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
ImGui::StyleColorsDark();
std::cout << "Dear ImGui version: " << IMGUI_VERSION << std::endl;
std::cout << "ImGui OpenGL (WebGL 2.0) Backend configured successfully!" << std::endl;
// Run the main loop (1 — simulates infinite loop in browser)
emscripten_set_main_loop(loop, 1, 1);
// Cleanup ImGui context
ImGui::DestroyContext();
return 0;
}
2. File Contents for CMakeLists.txt 2. Содержимое файла CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif()
project(imgui_opengl_wasm_test CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# -----------------------------------------------------------------------------
# Paths
# -----------------------------------------------------------------------------
set(IMGUI_DIR "C:/libs/imgui-1.93.0")
# -----------------------------------------------------------------------------
# Sources
# -----------------------------------------------------------------------------
set(IMGUI_SOURCES
${IMGUI_DIR}/imgui.cpp
${IMGUI_DIR}/imgui_draw.cpp
${IMGUI_DIR}/imgui_tables.cpp
${IMGUI_DIR}/imgui_widgets.cpp
${IMGUI_DIR}/backends/imgui_impl_opengl3.cpp
)
# -----------------------------------------------------------------------------
# Executable Target
# -----------------------------------------------------------------------------
add_executable(app
main.cpp
${IMGUI_SOURCES}
)
# -----------------------------------------------------------------------------
# Include Directories
# -----------------------------------------------------------------------------
target_include_directories(app PRIVATE
${IMGUI_DIR}
${IMGUI_DIR}/backends
)
# -----------------------------------------------------------------------------
# Backend Selection & Definitions
# -----------------------------------------------------------------------------
target_compile_definitions(app PRIVATE
IMGUI_IMPL_OPENGL_ES3
)
# -----------------------------------------------------------------------------
# Emscripten Linker Flags (WebGL 2.0 / GLES3)
# -----------------------------------------------------------------------------
target_link_options(app PRIVATE
"-sMAX_WEBGL_VERSION=2"
"-sMIN_WEBGL_VERSION=2"
"-sFULL_ES3=1"
"-sALLOW_MEMORY_GROWTH=1"
)
Step 5: Create Build & Execution Scripts Шаг 5: Создание скриптов сборки и запуска
Windows (Emscripten / Batch Scripts)
config-web.bat
call emcmake cmake -G "MinGW Makefiles" -S . -B dist/web
build-web.bat
call emmake cmake --build dist/web
run-web.bat
@echo off
node dist/web/app.js
Run the scripts sequentially in Command Prompt: Последовательно запустите скрипты в командной строке:
config-web.bat
build-web.bat
run-web.bat
Step 6: Expected Output Шаг 6: Ожидаемый результат
After running the build and execution scripts, the application will initialize Dear ImGui with the OpenGL (WebGL 2.0) backend and output the following lines to your terminal: После запуска скриптов сборки и выполнения приложение инициализирует Dear ImGui с бэкендом OpenGL (WebGL 2.0) и выведет следующие строки в терминал:
Dear ImGui version: 1.93.0
ImGui OpenGL (WebGL 2.0) Backend configured successfully!
Y if prompted), or simply close the command prompt window.
Совет: Локальный веб-сервер будет продолжать работать в терминале. Чтобы остановить его в любой момент, нажмите Ctrl + C в консоли (и введите Y при запросе) или просто закройте окно командной строки.
Step 7: Next Steps Шаг 7: Следующие шаги
Now that you have configured and verified Dear ImGui with WebGL 2.0, you can integrate it into your SDL3 WebAssembly projects: Теперь, когда вы настроили и проверили Dear ImGui с WebGL 2.0, вы можете перейти к интеграции библиотеки в свои WebAssembly-проекты на SDL3:
Support My Work Поддержать проект
If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.
Sberbank (Russia only) Сбербанк (только для РФ)
Direct transfer via phone number (Russia only) Перевод по номеру телефона (только для РФ)
USDT TRC20
Support via Cryptocurrency Поддержка криптовалютой