Skip to content

Engine Core

MichaelFisher1997 edited this page Jan 5, 2026 · 1 revision

Engine Core

Core engine systems providing foundational functionality: window management, timing, logging, and multithreaded job processing.


Window Management

File: src/engine/core/window.zig

Manages the application window lifecycle using SDL3 with Vulkan support and HiDPI awareness.

WindowManager

Field Type Description
window *c.SDL_Window SDL window handle
is_vulkan bool Vulkan rendering mode (default: true)

Key Functions

Function Description
init(allocator, use_vulkan, width, height) Initialize SDL, create resizable Vulkan window
setSize(width, height) Resize window (handles maximized/fullscreen states)
deinit() Destroy window and quit SDL

Time Management

File: src/engine/core/time.zig

Provides frame timing, delta time calculation, fixed timestep for physics, and FPS tracking.

Time Struct

Field Type Description
delta_time f32 Seconds since last frame
fixed_delta_time f32 Fixed timestep (default: 1/60s)
accumulator f32 Accumulated time for fixed updates
elapsed f32 Total elapsed seconds
frame_count u64 Total frames rendered
fps f32 Current FPS (updated per second)

Key Functions

Function Description
init() Initialize with current performance counter
update() Calculate delta, update FPS (clamps to 0.25s max)
shouldFixedUpdate() Returns true if fixed update should run
getAlpha() Interpolation factor for smooth rendering

Fixed Timestep Pattern

time.update();
while (time.shouldFixedUpdate()) {
    physics.fixedUpdate(time.fixed_delta_time);
}
render(time.getAlpha());  // Interpolate for smoothness

Logging System

File: src/engine/core/log.zig

Engine-wide logging with configurable severity levels.

LogLevel

pub const LogLevel = enum { trace, debug, info, warn, err, fatal };

Usage

const log = @import("log.zig");

log.log.info("Player spawned at ({}, {})", .{x, z});
log.log.err("Failed to load chunk: {}", .{error});

Global Instance

pub var log = Logger.init(.debug);  // Default minimum level

Job System

File: src/engine/core/job_system.zig

Thread-safe priority queue and worker pool for offloading expensive operations (world generation, mesh building).

Job Types

pub const JobType = enum { generation, meshing };

Job Structure

Field Type Description
type JobType Generation or meshing
chunk_x, chunk_z i32 Chunk coordinates
job_token u32 Unique token for validation
dist_sq i32 Priority (squared distance to player)

JobQueue

Priority queue with distance-based ordering (closer chunks processed first).

Method Description
init(allocator) Create queue
push(job) Add job to queue
pop() Blocking pop of highest priority job
updatePlayerPos(cx, cz) Update priority calculations
setPaused(paused) Pause/resume processing
stop() Signal shutdown

WorkerPool

Spawns threads that consume from a JobQueue.

const pool = try WorkerPool.init(
    allocator,
    4,                    // Thread count
    &job_queue,
    context,              // User context
    processJobFn,         // Callback
);
defer pool.deinit();

Lazy Reprioritization

When player moves significantly, jobs are re-sorted:

  • Threshold: 64 pending jobs minimum
  • Prevents constant re-sorting overhead

Ring Buffer

File: src/engine/core/ring_buffer.zig

Generic single-producer single-consumer FIFO queue with O(1) operations and auto-growth.

RingBuffer(T)

Field Type Description
buffer []T Backing storage
head usize Read position
tail usize Write position
len usize Current item count

Key Functions

Function Description
init(allocator, capacity) Create with initial capacity (min 64)
push(item) Add to back (auto-grows if full)
pop() Remove and return front (null if empty)
peek() View front without removing
clear() Clear without deallocation

Usage Example

var queue = try RingBuffer(*ChunkData).init(allocator, 256);
defer queue.deinit();

queue.push(chunk_data);
while (queue.pop()) |data| {
    uploadToGPU(data);
}

Core Interfaces

File: src/engine/core/interfaces.zig

VTable-based interfaces for polymorphic behavior following SOLID principles.

Available Interfaces

Interface Methods Purpose
IUpdatable update(dt) Frame updates
IRenderable render(view_proj) Rendering
IInputHandler handleInput(event) Input processing
IWidget draw(), handleInput(), getBounds() UI widgets
IChunkProvider generateChunk(x, z, blocks) World gen abstraction
IMeshBuilder buildMesh(blocks, verts, indices) Mesh strategies

Input Event Types

pub const InputEvent = union(enum) {
    key: KeyEvent,
    mouse_motion: MouseMotionEvent,
    mouse_button: MouseButtonEvent,
    mouse_scroll: MouseScrollEvent,
    window_resize: WindowResizeEvent,
    quit: void,
};

Key Enum

Comprehensive key definitions including:

  • Letters: a through z
  • Numbers: n0 through n9
  • Arrows: up, down, left, right
  • Modifiers: shift, ctrl, alt
  • Function keys: f1 through f12
  • Special: escape, space, tab, backspace, enter

Module Dependencies

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   std lib   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚                  β”‚                  β”‚
        β–Ό                  β–Ό                  β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ log.zig β”‚       β”‚ time.zig β”‚      β”‚ ring_buffer β”‚
   β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜       β”‚  (SDL3)  β”‚      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β–Ό                  
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚window.zig│◄─────│    c.zig    β”‚
   β”‚  (SDL3)  β”‚      β”‚  (SDL3/VK)  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚
        β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚  job_system  β”‚
   β”‚ (chunk.zig)  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

See Also


Source: src/engine/core/ | Last updated: January 2026

Clone this wiki locally