Overview
MaikEngine is a low-level 3D rendering and simulation engine written from scratch in C++20 using the Vulkan 1.3 graphics API. Built to explore modern graphics programming without legacy abstractions, the engine prioritizes explicit GPU control, cache-friendly data structures, and production-grade rendering paradigms aimed at indie video game development.
Unlike traditional engines anchored to OpenGL or older Vulkan 1.0 patterns, MaikEngine is designed around modern Vulkan 1.3 standards—leveraging Dynamic Rendering (VK_KHR_dynamic_rendering) to completely eliminate legacy VkRenderPass and VkFramebuffer boilerplate, Vulkan Memory Allocator (VMA) for GPU memory pooling, and glTF 2.0 streaming with KTX2 / Basis Universal hardware texture compression.
Video Demonstration
Demonstration of MaikEngine's capabilities at Phase 0
Architecture & Core Features
1. Modern Vulkan 1.3 Dynamic Rendering Pipeline
- Dynamic Rendering (
VK_KHR_dynamic_rendering): Eliminates rigidVkRenderPassandVkFramebufferstate objects. Passes declare color, depth, and stencil attachments on-the-fly viavkCmdBeginRendering/vkCmdEndRendering. - Multi-Pass Frame Orchestration:
- Pass 0 — Directional Shadow Mapping: Renders scene geometry to a dedicated 2048x2048
D32_SFLOATdepth target from sunlight view-projection. - Pass 1 — Depth Pre-Pass: Populates the primary depth buffer (
D32_SFLOAT) using specialized opaque and alpha-tested pipelines, setting up the GPU for optimal Early-Z rejection. - Pass 2 — PBR Shading & Alpha Cutout: Renders geometry with Cook-Torrance BRDF specular shading, sampling shadow maps and material textures.
- Pass 3 — Debug Overlay (ImGui): Renders immediate-mode UI controls directly into the active swapchain attachment.
- Pass 0 — Directional Shadow Mapping: Renders scene geometry to a dedicated 2048x2048
- Double-Buffered Frame Ring (
FRAME_OVERLAP = 2): Overlaps CPU command recording with GPU rendering using per-frame command pools, semaphores, and fences.
2. Physically-Based Shading (PBR)
- Cook-Torrance Microfacet BRDF: Evaluates specular reflection using GGX/Trowbridge-Reitz normal distribution (), Smith geometric shadowing (), and Schlick Fresnel approximation ().
- Metallic-Roughness Workflow: Extracts packed metalness (blue channel) and perceptual roughness (green channel) maps modulated by material factors.
- Alpha Cutout Pipelines: Dedicated shader variants and pipeline states (
standard_alpha.frag,depth_alpha.frag) utilizing alpha testing thresholds to handle complex vegetation and foliage geometry without sorting artifacts. - Percentage-Closer Filtered (PCF) Shadows: 3x3 kernel PCF sampling with texel bias correction for soft directional sunlight shadows.
3. Resource & Memory Management
- Vulkan Memory Allocator (VMA): Suballocates staging buffers, geometry buffers, and image memory from driver memory pools, preventing GPU memory exhaustion.
- Descriptor Management:
DescriptorAllocator: Dynamically manages pools with automatic exhaustion handling and growth.DescriptorLayoutCache: HashesVkDescriptorSetLayoutCreateInfoconfigurations to deduplicate descriptor set layouts across pipelines.- Clean two-tier descriptor architecture: Set 0 for global frame/camera/shadow data; Set 1 for per-material textures (Albedo, Metallic-Roughness, Normal).
4. High-Performance glTF 2.0 & Asset Streaming
- High-Speed glTF Parsing (
fastgltf): SIMD-accelerated glTF 2.0 decoding supporting external and embedded buffers/images. - Hardware Compressed Textures (
libktx/ KTX2): Detects and transcodes Basis Universal textures directly into hardware-nativeBC7_RGBAformat on the fly, dramatically slashing VRAM footprint and memory bandwidth. - GPU Mipmap Generation: Generates full mipmap pyramids at load time using asynchronous
vkCmdBlitImagetransfer barriers with linear downsampling.
5. Spatial Visibility & Camera Systems
- Gribb-Hartmann Frustum Culling: Extracts 6 normalized frustum planes directly from the active camera view-projection matrix.
- AABB Bounding Box Tests: Transforms local submesh bounding volumes by world-space model matrices on the CPU to cull off-screen geometry before dispatching draw calls.
- Camera System: Free-flight 6DOF camera with smooth Euler angle yaw/pitch clamping, perspective projection, and variable movement speed.
Challenges Solved
Drawing from the engine's development log and commit history on branch develop, several non-trivial engineering challenges were addressed:
Challenge 1: Swapchain Resizing, Alt-Tab Minimization & Tiling Window Managers
- The Problem: On tiling window managers (e.g. Hyprland on Linux) and during rapid window resizing or Alt-Tab minimize/restore cycles, Vulkan drivers throw
VK_ERROR_OUT_OF_DATE_KHRorVK_SUBOPTIMAL_KHR. Handling this naively caused synchronization deadlocks (vkWaitForFencestimeouts), framebuffer recreation crashes when extents dropped to(0, 0), and semaphore count mismatches. - The Solution:
- Refactored
Renderer::recreate_swapchain()to retire the old swapchain using.set_old_swapchain(old_swapchain)insidevkb::SwapchainBuilder. - Added strict extent guards skipping presentation and recreation when the window is minimized.
- Re-synchronized the depth buffer and per-swapchain-image
_renderSemaphoresarray dynamically. - Integrated runtime V-Sync toggling switching between
VK_PRESENT_MODE_FIFO_KHR(locked V-Sync) andVK_PRESENT_MODE_MAILBOX_KHR(low-latency triple buffering) without restart.
- Refactored
Challenge 2: glTF TRS Hierarchy & Multi-Primitive Geometry
- The Problem:
- glTF assets decompose models into hierarchies of nodes where transforms can be defined either as explicit matrices or decomposed Translation-Rotation-Scale (TRS) properties with unit quaternions.
- Early implementations produced disjointed geometry because quaternion rotations and node hierarchies were not properly transformed into column-major GLM matrix math.
- The Solution: Implemented a unified
std::visitvisitor pattern acrossfastgltf::TRScomponents, computing composite transform matrices () withglm::mat4_cast(glm::quat)and binding primitives with local AABB bounding volumes.
Challenge 3: Compressed Texture Streaming (KTX2 / BC7) & Mipmapping
- The Problem:
- Loading uncompressed 4K textures for large scenes like Sponza consumed excessive VRAM and caused severe texture aliasing/shimmering at distance.
- The Solution:
- Integrated
libktxto stream KTX2 files and transcode Universal Basis textures directly toBC7_RGBA_SRGB/BC7_RGBA_UNORMin VRAM. - Built an in-engine GPU mipmap generator using
vkCmdBlitImagewith progressive layout transitions (TRANSFER_DST_OPTIMALTRANSFER_SRC_OPTIMALSHADER_READ_ONLY_OPTIMAL) across all mip levels.
- Integrated
Challenge 4: Multi-Pipeline Depth Pre-Pass & Alpha Cutouts
- The Problem:
- Foliage, banners, and chainlink fences in glTF scenes require alpha cutout masking, which traditionally either causes sorting issues with alpha blending or overdraw costs with PBR evaluation.
- The Solution:
- Created a dual-pipeline strategy:
opaqueDepthPipeline(no fragment shader, hardware depth only) andalphaDepthPipeline(executesdepth_alpha.fragdiscarding fragments where ). - Ran the depth pre-pass ahead of the PBR pass, enabling the main PBR shader to run with depth writes disabled and early-Z fragment rejection.
- Created a dual-pipeline strategy:
Code Example: Vulkan 1.3 Dynamic Rendering & Multi-Pass Frame
// VulkanEngine.cpp: Multi-pass frame execution using Vulkan 1.3 Dynamic Rendering
void VulkanEngine::draw() {
BarrierData barrier_data = _renderer.begin_frame();
VkCommandBuffer cmd = barrier_data.cmd;
if (cmd == VK_NULL_HANDLE) return;
// 1. Update Camera / Light Uniform Buffer (Set 0)
GPUSceneData sceneData = compute_scene_matrices();
memcpy(currentFrame.cameraBuffer.info.pMappedData, &sceneData, sizeof(GPUSceneData));
// 2. PASS 0: Directional Shadow Mapping (2048x2048 D32_SFLOAT)
VkRenderingAttachmentInfo shadowAttachment{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = _renderer.get_shadow_image_view(),
.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = { .depthStencil = { .depth = 1.0f } }
};
VkRenderingInfo shadowPassInfo{
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = shadowScissor,
.layerCount = 1,
.pDepthAttachment = &shadowAttachment
};
vkCmdBeginRendering(cmd, &shadowPassInfo);
draw_geometry(cmd, visibleObjects, /*is_depth=*/true, /*is_shadow=*/true);
vkCmdEndRendering(cmd);
// Transition Shadow Map for Shader Reading
transition_image_layout(cmd, _renderer.get_shadow_image(),
VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// 3. PASS 1: Depth Pre-Pass (Early-Z Population)
VkRenderingAttachmentInfo depthAttachment{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = _renderer.get_depth_image_view(),
.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = { .depthStencil = { .depth = 1.0f } }
};
VkRenderingInfo depthPassInfo{
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = barrier_data.scissor,
.layerCount = 1,
.pDepthAttachment = &depthAttachment
};
vkCmdBeginRendering(cmd, &depthPassInfo);
draw_geometry(cmd, visibleObjects, /*is_depth=*/true, /*is_shadow=*/false);
vkCmdEndRendering(cmd);
// 4. PASS 2: PBR Forward Pass (Depth Tested, Color Output)
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // Reuse depth pre-pass
VkRenderingAttachmentInfo colorAttachment{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = _renderer.get_swapchain_image_view(),
.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = { .color = { 0.1f, 0.2f, 0.4f, 1.0f } }
};
VkRenderingInfo pbrPassInfo{
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = barrier_data.scissor,
.layerCount = 1,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAttachment,
.pDepthAttachment = &depthAttachment
};
vkCmdBeginRendering(cmd, &pbrPassInfo);
draw_geometry(cmd, visibleObjects, /*is_depth=*/false, /*is_shadow=*/false);
// 5. PASS 3: Dear ImGui Dynamic Rendering
_imguiManager.begin_frame();
render_debug_gui();
_imguiManager.end_frame(cmd);
vkCmdEndRendering(cmd);
// Transition Swapchain to Present Layout and Submit
_renderer.end_frame();
}
Project Structure
app/src/MaikEngine/
├── Core/
│ ├── VulkanEngine.h/.cpp # Engine coordinator & frame pass orchestration
│ ├── InputManager.h/.cpp # SDL3 keyboard & relative mouse capture
│ ├── ISystem.h # Subsystem lifecycle interface
│ └── main.h/.cpp # Application entry point
├── Renderer/
│ ├── VulkanContext.h/.cpp # Instance, Device, Queue & VMA allocator lifecycle
│ ├── Renderer.h/.cpp # Swapchain, Synchronization & Render Targets
│ ├── PipelineBuilder.h # Fluent Vulkan 1.3 Graphics Pipeline Builder
│ ├── DescriptorAllocator.h/.cpp# Dynamic Descriptor Pool allocator
│ ├── DescriptorBuilder.h/.cpp # Descriptor Set Layout cache & fluent builder
│ └── VulkanTypes.h # GPU data structs, Push Constants, Uniforms
├── Scene/
│ ├── SceneManager.h/.cpp # Scene object collection & CPU frustum culling
│ ├── RenderObject.h # Vertex, Mesh, Material & AABB definitions
│ ├── CameraManager.h/.cpp # Camera controller & Gribb-Hartmann extraction
│ └── Camera.h/.cpp # 6DOF View & Projection matrices
├── Resources/
│ ├── ResourceManager.h/.cpp # VMA buffers/images, fastgltf & libktx loader
│ └── stb_image.cpp # Image loader implementation unit
└── UI/
└── ImGuiManager.h/.cpp # Dear ImGui Vulkan 1.3 dynamic rendering wrapper
Technical Specifications & Stack
| Component | Technology | Detail |
|---|---|---|
| Language Standard | C++20 | Concepts, designated initializers, smart pointers, RAII. |
| Graphics API | Vulkan 1.3 | Explicit Dynamic Rendering (VK_KHR_dynamic_rendering), no render passes. |
| Memory Allocation | Vulkan Memory Allocator (VMA) | Suballocated device-local and host-visible GPU memory pools. |
| Windowing & Input | SDL3 (3.4+) | Native window creation, Vulkan surface, raw mouse/keyboard events. |
| Asset Parsing | fastgltf (0.9+) | SIMD glTF 2.0 asset streaming (buffers, accessors, materials). |
| Texture Formats | libktx (4.x) & stb_image | KTX2 / Basis Universal transcoding to BC7; PNG/JPG fallback. |
| Math Library | GLM | Column-major linear algebra, quaternions, perspective math. |
| Shading Language | GLSL 450 / SPIR-V | Compiled via offline CMake custom target using Google glslc. |
| Debug UI | Dear ImGui (1.92 Docking) | Immediate-mode UI overlay rendered directly via dynamic rendering. |
| Build System | Modern CMake (4.x / Ninja) | Multi-configuration build targets with automated shader pipelines. |
Roadmap & Next Milestones
Current Phase: Stabilization & Visual Quality (In Progress)
- Modern Vulkan 1.3 Dynamic Rendering core with double buffering.
- Complete Cook-Torrance PBR BRDF with metallic/roughness workflow.
- glTF 2.0 scene loading with KTX2 / Basis Universal texture decompression.
- GPU mipmap generation pyramid via blit transfers.
- CPU Frustum Culling with AABB Gribb-Hartmann plane extraction.
- Multi-pass architecture: Directional Shadow Mapping + Depth Pre-Pass + PBR.
- Resilient swapchain recreation handling tiling window managers and Alt-Tab.
- Stabilization Fixes: Resolve Early-Z hardware suppression flag and full teardown cleanup.
- MikkTSpace Tangents: Compute accurate vertex tangent vectors at import to replace derivative-based normal calculation.
Upcoming Phase: Vulkan 1.3 Overhaul & Advanced Graphics
- Render Graph (Frame Graph): Declarative pass specification with automated barrier insertion and memory aliasing.
- Vulkan 1.3 Bindless Descriptors: Global unbounded texture arrays (
u_Textures[]) eliminating per-material descriptor set allocations. - Unified Geometry Mega-Buffers: Single consolidated vertex/index buffer suballocations removing per-mesh buffer binds.
- Cascaded Shadow Maps (CSM): 3-4 frustum splits with PCF Poisson disk filtering.
- Image-Based Lighting (IBL): Irradiance convolution, prefiltered environment maps, and split-sum BRDF LUT.
- HDR & Post-Processing Pipeline: Offscreen
R16G16B16A16Ffloating-point target, Kawase Bloom, and ACES/AgX tone mapping.
Long-Term Phase: Game Engine Architecture
- Entity-Component-System (ECS): Integration of EnTT for high-performance, cache-coherent gameplay data.
- Hierarchical Scene Graph: Parent-child transform propagation with dirty flag caching.
- GPU-Driven Rendering: Multi-Draw Indirect (
vkCmdDrawIndexedIndirectCount) and compute-driven Hi-Z occlusion culling. - Integrated Editor: ImGui Docking workspace with dedicated offscreen viewport and ImGuizmo 3D handles.
- Physics & Audio: Integration of Jolt Physics (rigid bodies, collisions) and MiniAudio (spatial 3D sound).