### Minimal build.zig Example (0.15.x) Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md A basic build script to create an executable from a source file and install it. This example demonstrates setting up standard target and optimization options, creating an executable, installing it, and setting up a run command with arguments. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "myapp", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_cmd.step); } ``` -------------------------------- ### Build Zig Example Suite Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Define a build step to compile multiple examples, importing a library and installing them into a specific directory. ```zig const examples = [_][]const u8{ "basic", "advanced", "demo" }; const examples_step = b.step("examples", "Build examples"); for (examples) |name| { const exe = b.addExecutable(.{ .name = name, .root_module = b.createModule(.{ .root_source_file = b.path(b.fmt("examples/{s}.zig", .{name})), .target = target, .optimize = optimize, }), }); exe.root_module.addImport("mylib", lib_mod); const install = b.addInstallArtifact(exe, .{ .dest_dir = .{ .custom = "examples" }, }); examples_step.dependOn(&install.step); } ``` -------------------------------- ### Using LazyPath for Build Configuration Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Shows practical examples of using LazyPath for setting the root source file, include paths, and installing files. ```zig // As source file exe.root_module.root_source_file = b.path("src/main.zig"); // As include path exe.addIncludePath(dep.path("include")); // Install b.installFile(generated_file, "share/output.txt"); ``` -------------------------------- ### Complete SDL3 Application with Callbacks Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/init-lifecycle.md A full example demonstrating the implementation of init, iterate, event, and quit callbacks for a basic SDL3 application in Zig. This includes window and renderer setup, drawing a player, handling keyboard input, and resource cleanup. ```zig const sdl3 = @import("sdl3"); const std = @import("std"); const allocator = std.heap.smp_allocator; const AppState = struct { window: sdl3.video.Window, renderer: sdl3.render.Renderer, fps_capper: sdl3.extras.FramerateCapper(f32), player_x: f32 = 400, player_y: f32 = 300, }; fn init(app_state: *?*AppState, args: [][*:0]u8) !sdl3.AppResult { _ = args; const window = try sdl3.video.Window.init("Callback Game", 800, 600, .{}); errdefer window.deinit(); const renderer = try sdl3.render.Renderer.init(window, null); errdefer renderer.deinit(); const state = try allocator.create(AppState); state.* = .{ .window = window, .renderer = renderer, .fps_capper = .{ .mode = .{ .limited = 60 } }, }; app_state.* = state; return .run; } fn iterate(state: *AppState) !sdl3.AppResult { const dt = state.fps_capper.delay(); _ = dt; // Clear try state.renderer.setDrawColor(.{ .r = 30, .g = 30, .b = 50, .a = 255 }); try state.renderer.clear(); // Draw player try state.renderer.setDrawColor(.{ .r = 255, .g = 100, .b = 100, .a = 255 }); try state.renderer.renderFillRect(.{ .x = state.player_x - 25, .y = state.player_y - 25, .w = 50, .h = 50, }); try state.renderer.present(); return .run; } fn event(state: *AppState, ev: sdl3.events.Event) !sdl3.AppResult { switch (ev) { .quit, .terminating => return .success, .key_down => |k| { const speed: f32 = 10; switch (k.scancode) { .left, .a => state.player_x -= speed, .right, .d => state.player_x += speed, .up, .w => state.player_y -= speed, .down, .s => state.player_y += speed, .escape => return .success, else => {}, } }, else => {}, } return .run; } fn quit(app_state: ?*AppState, result: sdl3.AppResult) void { _ = result; if (app_state) |state| { state.renderer.deinit(); state.window.deinit(); allocator.destroy(state); } } pub fn main() u8 { sdl3.main_funcs.setMainReady(); var args = [_:null]?[*:0]u8{@constCast("My Game")}; return sdl3.main_funcs.enterAppMainCallbacks(&args, AppState, init, iterate, event, quit); } ``` -------------------------------- ### Configure build.zig for zig-sdl3 Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/getting-started.md Set up your build.zig file to include the zig-sdl3 dependency and link it to your executable. This example shows basic setup and a run step. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const sdl3_dep = b.dependency("sdl3", .{ .target = target, .optimize = optimize, }); const exe = b.addExecutable(.{ .name = "my-game", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); exe.root_module.addImport("sdl3", sdl3_dep.module("sdl3")); b.installArtifact(exe); // Run step const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_cmd.step); } ``` -------------------------------- ### Complete Example: Config Parser Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-static-string-map.md A comprehensive example showing case-insensitive parsing of configuration lines using StaticStringMap. ```zig const std = @import("std"); const ConfigKey = enum { host, port, debug, timeout, }; const config_keys = std.StaticStringMapWithEql( ConfigKey, std.static_string_map.eqlAsciiIgnoreCase, ).initComptime(.{ .{ "host", .host }, .{ "port", .port }, .{ "debug", .debug }, .{ "timeout", .timeout }, }); fn parseConfig(line: []const u8) ?struct { key: ConfigKey, value: []const u8 } { const eq_idx = std.mem.indexOf(u8, line, "=") orelse return null; const key_str = std.mem.trim(u8, line[0..eq_idx], " "); const value = std.mem.trim(u8, line[eq_idx + 1 ..], " "); const key = config_keys.get(key_str) orelse return null; return .{ .key = key, .value = value }; } pub fn main() void { const lines = [_][]const u8{ "HOST = localhost", "PORT = 8080", "Debug = true", }; for (lines) |line| { if (parseConfig(line)) |cfg| { std.debug.print("{}: {s}\n", .{ cfg.key, cfg.value }); } } } ``` -------------------------------- ### Running zig-sdl3 Examples Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/getting-started.md Commands to list and run specific examples provided with the zig-sdl3 repository using `zig build run`. ```bash # List examples ls examples/ # Run specific example zig build run -Dexample=hello-world zig build run -Dexample=callbacks zig build run -Dexample=custom-allocator # Build all examples zig build examples ``` -------------------------------- ### Complete Example: HTTP Method Parser Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-static-string-map.md A full example demonstrating how to parse HTTP methods using a compile-time initialized StaticStringMap. ```zig const std = @import("std"); const Method = enum { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, }; const methods = std.StaticStringMap(Method).initComptime(.{ .{ "GET", .GET }, .{ "POST", .POST }, .{ "PUT", .PUT }, .{ "DELETE", .DELETE }, .{ "PATCH", .PATCH }, .{ "HEAD", .HEAD }, .{ "OPTIONS", .OPTIONS }, }); fn parseMethod(s: []const u8) ?Method { return methods.get(s); } pub fn main() void { if (parseMethod("POST")) |m| { std.debug.print("Method: {}\n", .{m}); // Method: POST } if (parseMethod("INVALID")) |_| { unreachable; } else { std.debug.print("Invalid method\n", .{}); } } ``` -------------------------------- ### Zig SDL3 Tray Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/dialogs-ui.md This snippet shows a complete example of initializing a system tray icon, creating a context menu with various options (show window, toggle notifications, quit), and handling callbacks for each menu item. It includes the necessary state management for the application. ```zig const AppState = struct { tray: sdl3.tray.Tray, running: bool = true, notifications: bool = true, fn init() !AppState { const icon = try sdl3.surface.Surface.loadBmp("app_icon.bmp"); defer icon.deinit(); const tray = try sdl3.tray.Tray.init(icon, "My App - Running"); const menu = try tray.createMenu(); var state = AppState{ .tray = tray }; // Build menu if (menu.insertAt(null, "Show", .{ .entry = .{ .button = {} } })) |e| { e.setCallback(AppState, showWindow, &state); } if (menu.insertAt(null, "Notifications", .{ .entry = .{ .checkbox = true } })) |e| { e.setCallback(AppState, toggleNotifications, &state); } _ = menu.insertAt(null, null, .{ .entry = .{ .button = {} } }); // separator if (menu.insertAt(null, "Quit", .{ .entry = .{ .button = {} } })) |e| { e.setCallback(AppState, quit, &state); } return state; } fn deinit(self: *AppState) void { self.tray.deinit(); } fn showWindow(state: ?*AppState, entry: sdl3.tray.Entry) void { _ = entry; _ = state; // Show main window } fn toggleNotifications(state: ?*AppState, entry: sdl3.tray.Entry) void { if (state) |s| { s.notifications = entry.getChecked(); } } fn quit(state: ?*AppState, entry: sdl3.tray.Entry) void { _ = entry; if (state) |s| { s.running = false; } } }; ``` -------------------------------- ### Full build.zig.zon Package Manifest Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md A complete example of a `build.zig.zon` file, demonstrating package name, version, minimum Zig version, dependencies (URL, local, lazy), and included paths. ```zig .{ // Package name (required) .name = "my_project", // Semantic version (required) .version = "1.2.3", // Minimum Zig version (optional) .minimum_zig_version = "0.15.0", // Dependencies (optional) .dependencies = .{ // URL dependency with hash ."zig-network" = .{ .url = "https://github.com/user/zig-network/archive/v1.0.0.tar.gz", .hash = "12205f17c...", }, // Local path dependency .local_dep = .{ .path = "../other-project", }, // Lazy dependency (only fetched if used) .optional_dep = .{ .url = "https://example.com/dep.tar.gz", .hash = "1220abc...", .lazy = true, }, }, // Files included in package (required for publishing) .paths = .{ "build.zig", "build.zig.zon", "src", "LICENSE", "README.md", }, } ``` -------------------------------- ### Example Prompt for Zig Skill Usage Source: https://github.com/rudedogg/zig-skills/blob/main/README.md This example demonstrates how to invoke the Zig Agent Skill to review and improve a codebase. Ensure the skill is installed in the correct directory. ```plaintext Using the zig skill please review @src/ and help me improve the codebase. ``` -------------------------------- ### Zig build.zig Setup for raylib-zig Source: https://github.com/rudedogg/zig-skills/blob/main/zig-raylib/SKILL.md Configure your build.zig file to include the raylib-zig dependency, add the raylib module, and link the library. This example also shows how to optionally add raygui. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // Get raylib-zig dependency const raylib_dep = b.dependency("raylib_zig", .{ .target = target, .optimize = optimize, }); const exe = b.addExecutable(.{ .name = "my-game", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); // Add raylib module and link library exe.root_module.addImport("raylib", raylib_dep.module("raylib")); exe.root_module.linkLibrary(raylib_dep.artifact("raylib")); // Optional: add raygui for GUI widgets exe.root_module.addImport("raygui", raylib_dep.module("raygui")); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the game"); run_step.dependOn(&run_cmd.step); } ``` -------------------------------- ### ZON Build Configuration File Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-zon.md Example of a `build.zig.zon` file used for project configuration, defining name, version, dependencies, and paths. It demonstrates how to import and access these configurations in `build.zig` at comptime. ```zig // build.zig.zon .{ .name = "my-project", .version = "0.1.0", .dependencies = .{ .zap = .{ .url = "https://github.com/...", .hash = "...", }, }, .paths = .{ "src", "build.zig", "build.zig.zon" }, } ``` ```zig // build.zig - reading build.zig.zon at comptime const build_zon = @import("build.zig.zon"); const project_name = build_zon.name; ``` -------------------------------- ### Basic Thread Spawn Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-thread.md Demonstrates how to spawn a new thread and wait for its completion using `spawn` and `join`. ```zig const std = @import("std"); fn workerFn(id: usize) void { std.debug.print("Worker {d} running\n", .{id}); } pub fn main() !void { const thread = try std.Thread.spawn(.{}, workerFn, .{42}); thread.join(); // wait for completion } ``` -------------------------------- ### Complete std.Treap Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-treap.md A full example demonstrating initialization, insertion, lookup, neighbor access, iteration, and removal of elements in a std.Treap. ```zig const std = @import("std"); const Treap = std.Treap(u64, std.math.order); pub fn main() !void { var treap: Treap = .{}; var nodes: [10]Treap.Node = undefined; // Insert keys 0-9 for (0..10) |i| { var entry = treap.getEntryFor(@intCast(i)); entry.set(&nodes[i]); } // Find key 5 var entry = treap.getEntryFor(5); if (entry.node) |node| { std.debug.print("found: {}\n", .{node.key}); // Get neighbors if (node.prev()) |p| std.debug.print("prev: {}\n", .{p.key}); if (node.next()) |n| std.debug.print("next: {}\n", .{n.key}); } // Iterate in order var iter = treap.inorderIterator(); while (iter.next()) |node| { std.debug.print("{} ", .{node.key}); } // Output: 0 1 2 3 4 5 6 7 8 9 // Remove key 5 entry.set(null); } ``` -------------------------------- ### Complete Example: Environment Variables with std.BufMap Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-buf-map.md A full example demonstrating how to use std.BufMap to store and manage environment-like variables. It shows setting, updating, iterating, and checking for specific variables, with automatic memory management for keys and values. ```zig const std = @import("std"); pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa.deinit(); const alloc = gpa.allocator(); var env = std.BufMap.init(alloc); defer env.deinit(); // Set some variables try env.put("APP_NAME", "MyApp"); try env.put("APP_VERSION", "1.0.0"); try env.put("DEBUG", "true"); // Update a value try env.put("DEBUG", "false"); // replaces, frees old value // Print all var it = env.iterator(); while (it.next()) |entry| { std.debug.print("{s}={s} ", .{ entry.key_ptr.* entry.value_ptr.* }); } // Check and use if (env.get("DEBUG")) |debug| { if (std.mem.eql(u8, debug, "true")) { std.debug.print("Debug mode enabled ", .{ }); } } } ``` -------------------------------- ### Complete Example: Task Scheduler with Priority Queue Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-priority-queue.md A full example demonstrating a task scheduler using a priority queue. Tasks are structs with names and priorities, and the queue processes them in order of urgency (lower priority number first). ```zig const std = @import("std"); const Task = struct { name: []const u8, priority: u32, // lower = more urgent }; fn taskCompare(_: void, a: Task, b: Task) std.math.Order { return std.math.order(a.priority, b.priority); } const TaskQueue = std.PriorityQueue(Task, void, taskCompare); pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa.deinit(); var tasks = TaskQueue.init(gpa.allocator(), {}); defer tasks.deinit(); try tasks.add(.{ .name = "low priority", .priority = 100 }); try tasks.add(.{ .name = "urgent", .priority = 1 }); try tasks.add(.{ .name = "medium", .priority = 50 }); while (tasks.removeOrNull()) |task| { std.debug.print("Processing: {s}\n", .{task.name}); } // Output: // Processing: urgent // Processing: medium // Processing: low priority } ``` -------------------------------- ### Permission Flags Example using StaticBitSet Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-bit-set.md A complete example demonstrating the use of StaticBitSet for managing permission flags, including granting, revoking, and checking permissions using enum values. ```zig const std = @import("std"); const Permission = enum(u8) { read = 0, write = 1, execute = 2, delete = 3, admin = 4, }; const Permissions = std.StaticBitSet(8); fn hasPermission(perms: Permissions, p: Permission) bool { return perms.isSet(@intFromEnum(p)); } fn grant(perms: *Permissions, p: Permission) void { perms.set(@intFromEnum(p)); } fn revoke(perms: *Permissions, p: Permission) void { perms.unset(@intFromEnum(p)); } pub fn main() void { var user_perms = Permissions.initEmpty(); grant(&user_perms, .read); grant(&user_perms, .write); var admin_perms = Permissions.initFull(); // Check if user has all admin permissions if (user_perms.subsetOf(admin_perms)) { // user can do everything admin can (not in this case) } // Grant user all of admin's permissions user_perms.setUnion(admin_perms); } ``` -------------------------------- ### Cross-Compilation Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/SKILL.md Shows how to use Zig's cross-compilation capabilities to build for different target platforms. ```bash zig build -Dtarget=x86_64-windows zig build -Dtarget=aarch64-macos zig build -Dtarget=wasm32-emscripten ``` -------------------------------- ### Full Allocator Naming Example for Request Handling Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-allocators.md Shows a comprehensive example of using 'arena', 'gpa', and 'scratch' allocators within a request handler function to manage memory with different lifetimes and purposes. ```zig const Allocator = std.mem.Allocator; fn handleRequest( request: *Request, arena: Allocator, // Response lifetime - bulk freed after response sent gpa: Allocator, // Long-lived data - cache, shared state scratch: Allocator, // This function only - intermediate computation ) !Response { // Scratch: temporary parsing buffers (never escapes this function) const parsed = try parseBody(request.body, scratch); // GPA: update shared cache (outlives request) try updateCache(gpa, parsed.cache_key, parsed.value); // Arena: response data (freed when response completes) const response_body = try formatResponse(arena, parsed); return Response{ .body = response_body }; } ``` -------------------------------- ### Initialize Window, Audio, and Load Resources Source: https://github.com/rudedogg/zig-skills/blob/main/zig-raylib/references/api-resources.md Provides a structured example of initializing the game window and audio device before loading resources, ensuring proper order of operations. ```zig pub fn main() !void { // 1. Initialize window first rl.initWindow(800, 600, "Game"); defer rl.closeWindow(); // 2. Initialize audio if needed rl.initAudioDevice(); defer rl.closeAudioDevice(); // 3. Load resources (after window init) const texture = try rl.loadTexture("sprite.png"); defer rl.unloadTexture(texture); const sound = try rl.loadSound("jump.wav"); defer rl.unloadSound(sound); // 4. Game loop while (!rl.windowShouldClose()) { // ... } } ``` -------------------------------- ### Swapchain Setup Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/gpu.md Details on how to set up the swapchain after claiming a window, including querying texture formats and configuring present modes and compositions. ```APIDOC ## Swapchain Setup After claiming a window, query swapchain properties: ```zig // Claim window first try device.claimWindow(window); // Get swapchain texture format for pipeline creation const swapchain_format = try device.getSwapchainTextureFormat(window); // Configure present mode and composition try device.setSwapchainParameters(window, .sdr, .vsync); // Available present modes: // .vsync - Sync to display refresh, no tearing // .mailbox - Lowest latency, may drop frames // .immediate - No sync, may tear // .fifo - FIFO queue, smooth but more latency // .fifo_relaxed - FIFO with adaptive sync // Available compositions: // .sdr - Standard dynamic range // .sdr_linear - SDR with linear transfer // .hdr_extended_linear - HDR with linear transfer // .hdr10_st2084 - HDR10 with PQ transfer ``` ``` -------------------------------- ### Benchmarking with Timer in Zig Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-time.md Utilize `std.time.Timer` for monotonic benchmarking. Use `start()` to initialize, `lap()` to get elapsed time since the last lap/reset and reset the timer, and `read()` to get the total elapsed time without resetting. ```zig const std = @import("std"); pub fn main() !void { var timer = try std.time.Timer.start(); // ... first phase ... const phase1_ns = timer.lap(); // read and reset // ... second phase ... const phase2_ns = timer.lap(); // Total since start timer.reset(); // ... final phase ... const total_ns = timer.read(); } ``` -------------------------------- ### Format Entire Zig Project Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/style-guide.md Apply the style guide formatting to all files within the current directory and its subdirectories. ```bash zig fmt . ``` -------------------------------- ### Resource Management with Defer Source: https://github.com/rudedogg/zig-skills/blob/main/zig-raylib/references/api-resources.md Demonstrates the recommended pattern for loading and unloading resources using `defer` to ensure proper cleanup after window initialization. ```zig pub fn main() !void { rl.initWindow(800, 600, "Game"); defer rl.closeWindow(); // Load resources after window init const texture = try rl.loadTexture("sprite.png"); defer rl.unloadTexture(texture); const sound = try rl.loadSound("jump.wav"); defer rl.unloadSound(sound); // Game loop... } ``` -------------------------------- ### Get Global Mouse Position Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/mouse.md Retrieves the current global screen coordinates of the mouse cursor. No setup is required beyond importing the sdl3 library. ```zig _, const screen_x, const screen_y = sdl3.mouse.getGlobalState(); ``` -------------------------------- ### TCP Server Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/net.md Set up a TCP server to listen on a specified port and handle incoming client connections by echoing data back. ```zig const sdl3 = @import("sdl3"); pub fn main() !void { // Create server socket const server = try sdl3.net.Server.init(null, 8080); // Listen on all interfaces defer server.deinit(); std.debug.print("Listening on port 8080...\n", .{}); while (true) { // Accept connection if (server.accept()) |client| { handleClient(client); } } } fn handleClient(socket: sdl3.net.StreamSocket) void { defer socket.deinit(); var buffer: [1024]u8 = undefined; while (true) { const bytes = socket.read(&buffer) catch break; if (bytes == 0) break; // Echo back socket.write(buffer[0..bytes]) catch break; } } ``` -------------------------------- ### Audio Playback Example Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/SKILL.md Demonstrates loading a WAV file, opening an audio device, creating and binding an audio stream, queuing audio data, and resuming playback. ```zig const sdl3 = @import("sdl3"); // Load WAV file (returns tuple: Spec + data) const spec, const audio_buf = try sdl3.audio.loadWav("sound.wav"); defer sdl3.free(audio_buf.ptr); // Open audio device const device = try sdl3.audio.Device.default_playback.open(spec); defer device.close(); // Create stream and bind to device const stream = try sdl3.audio.Stream.init(spec, spec); defer stream.deinit(); try device.bindStream(stream); // Queue audio data try stream.putData(audio_buf); // Resume playback (devices start paused) try device.resumePlayback(); ``` -------------------------------- ### Traditional Main Loop Pattern in Zig-SDL3 Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/init-lifecycle.md Provides a complete example of the traditional SDL3 main loop, including initialization, window/renderer setup, event polling, updating, and rendering with frame rate control. ```zig const sdl3 = @import("sdl3"); pub fn main() !void { defer sdl3.shutdown(); try sdl3.init(.{ .video = true }); defer sdl3.quit(.{ .video = true }); const window = try sdl3.video.Window.init("Game", 800, 600, .{}); defer window.deinit(); const renderer = try sdl3.render.Renderer.init(window, null); defer renderer.deinit(); // Frame rate control var fps_capper = sdl3.extras.FramerateCapper(f32){ .mode = .{ .limited = 60 }, }; var running = true; while (running) { const dt = fps_capper.delay(); // Process events while (sdl3.events.poll()) |event| { switch (event) { .quit => running = false, else => {}, } } // Update update(dt); // Render try renderer.setDrawColor(.{ .r = 0, .g = 0, .b = 0, .a = 255 }); try renderer.clear(); render(renderer); try renderer.present(); } } fn update(dt: f32) void { // Update game state _ = dt; } fn render(renderer: sdl3.render.Renderer) void { // Draw game _ = renderer; } ``` -------------------------------- ### Zig SDL3 Stream Seeking and Size Operations Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/filesystem-io.md Demonstrates how to seek to specific positions (from start, relative to current, from end) within a stream, get the current position, and retrieve the total size of the stream. ```zig const sdl3 = @import("sdl3"); // Assuming 'stream' is an initialized sdl3.io_stream.Stream object // Seek to position (returns new position) const new_pos = try stream.seek(100, .set); // From start _ = try stream.seek(-10, .cur); // Relative to current _ = try stream.seek(0, .end); // From end // Get current position const pos = try stream.tell(); // Get size const size = try stream.getSize(); ``` -------------------------------- ### Audio Recording Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/audio.md Provides an example of how to record audio using SDL3's default recording device. It covers initializing the audio subsystem, opening a recording stream, starting the device, capturing audio data for a specified duration, and storing it. ```APIDOC ## Audio Recording ### Description Captures audio input from the system's default recording device. This example demonstrates setting up the audio specifications, opening the recording stream, and continuously capturing audio data into a buffer for a set duration. ### Initialization - Initialize SDL audio: `sdl3.init(.{ .audio = true })` - Define audio specifications: `sdl3.audio.Spec` (format, channels, sample rate) ### Recording Process - Open recording stream: `sdl3.audio.Device.default_recording.openStream(spec, ...)` - Start recording device: `stream.resumeDevice()` - Capture data in a loop: `stream.getData(&buffer)` - Store captured data (e.g., in `std.ArrayList(u8)`) - Stop recording after a duration (e.g., 5 seconds using `sdl3.timer.getMillisecondsSinceInit()`) ### Cleanup - Deinitialize stream: `stream.deinit()` - Quit SDL audio: `sdl3.quit(.{ .audio = true })` ``` -------------------------------- ### Window Creation with Flags Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/video-windows.md Demonstrates initializing an SDL3 window with a comprehensive set of flags for display, rendering, HiDPI, and behavior. ```zig const window = try sdl3.video.Window.init("Game", 1920, 1080, .{ // Display mode .fullscreen = true, // Fullscreen exclusive .borderless = true, // No window decorations .resizable = true, // User can resize .minimized = true, // Start minimized .maximized = true, // Start maximized // Rendering .open_gl = true, // Create OpenGL context .vulkan = true, // Create Vulkan surface .metal = true, // Create Metal layer // HiDPI .high_pixel_density = true, // Request HiDPI // Behavior .hidden = true, // Start hidden .always_on_top = true, // Stay above others .input_focus = true, // Grab keyboard focus .mouse_focus = true, // Grab mouse focus .mouse_grabbed = true, // Confine mouse to window .keyboard_grabbed = true, // Grab keyboard .mouse_relative_mode = true, // Relative mouse mode // Special .utility = true, // Utility window (no taskbar) .popup_menu = true, // Popup menu window .tooltip = true, // Tooltip window .not_focusable = true, // Cannot receive focus .transparent = true, // Transparent window }); ``` -------------------------------- ### Basic HTTP Server Setup in Zig Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-http.md Sets up a basic TCP server that listens for incoming HTTP connections and handles requests. It initializes a server instance and enters a loop to accept and process connections. ```zig const std = @import("std"); const net = std.net; const http = std.http; pub fn main() !void { const address = net.Address.initIp4(.{ 127, 0, 0, 1 }, 8080); var tcp_server = try address.listen(.{}); defer tcp_server.deinit(); while (true) { const conn = try tcp_server.accept(); defer conn.stream.close(); var read_buf: [8192]u8 = undefined; var write_buf: [4096]u8 = undefined; var reader = conn.stream.reader(&read_buf); var writer = conn.stream.writer(&write_buf); var server = http.Server.init(reader.interface(), &writer.interface); const request = server.receiveHead() catch |err| { std.debug.print("Failed to receive: { \n}", .{err}); continue; }; try handleRequest(&request); } } fn handleRequest(request: *http.Server.Request) !void { const head = request.head; std.debug.print("{s} {s}\n", .{@tagName(head.method), head.target}); // Simple response try request.respond("Hello, World!", .{ .status = .ok, .extra_headers = &.{ .{ .name = "Content-Type", .value = "text/plain" }, }, }); } ``` -------------------------------- ### Install Generated Documentation Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Installs generated documentation files to a specified directory, typically under the installation prefix. ```zig // Install documentation const docs_install = b.addInstallDirectory(.{ .source_dir = lib.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", }); const docs_step = b.step("docs", "Generate documentation"); docs_step.dependOn(&docs_install.step); ``` -------------------------------- ### Install Artifacts with Custom Options Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Installs artifacts to a custom directory and installs individual files or entire directories. ```zig // Install with custom options const install = b.addInstallArtifact(exe, .{ .dest_dir = .{ .custom = "tools" }, // zig-out/tools/ }); b.getInstallStep().dependOn(&install.step); // Install file b.installFile("assets/config.json", "share/config.json"); b.installBinFile("scripts/run.sh", "run.sh"); // Install directory b.installDirectory(.{ .source_dir = b.path("assets"), .install_dir = .{ .custom = "share" }, .install_subdir = "assets", }); ``` -------------------------------- ### Swapchain Setup and Configuration Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/gpu.md Configures the swapchain after claiming a window, querying its texture format, and setting presentation parameters like mode and composition. ```zig // Claim window first try device.claimWindow(window); // Get swapchain texture format for pipeline creation const swapchain_format = try device.getSwapchainTextureFormat(window); // Configure present mode and composition try device.setSwapchainParameters(window, .sdr, .vsync); // Available present modes: // .vsync - Sync to display refresh, no tearing // .mailbox - Lowest latency, may drop frames // .immediate - No sync, may tear // .fifo - FIFO queue, smooth but more latency // .fifo_relaxed - FIFO with adaptive sync // Available compositions: // .sdr - Standard dynamic range // .sdr_linear - SDR with linear transfer // .hdr_extended_linear - HDR with linear transfer // .hdr10_st2084 - HDR10 with PQ transfer ``` -------------------------------- ### Zig Get File Size Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-fs.md Gets the current size of an opened file in bytes. ```zig // Get file size const size = try file.getEndPos(); ``` -------------------------------- ### Zig Build Installation Paths Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Commands to specify custom installation prefixes and subdirectories for build artifacts. ```bash # Custom install prefix zig build -p /usr/local zig build --prefix=/opt/myapp # Custom subdirectories zig build --prefix-lib-dir=lib64 zig build --prefix-exe-dir=sbin ``` -------------------------------- ### Color Initialization and Utilities Source: https://github.com/rudedogg/zig-skills/blob/main/zig-raylib/SKILL.md Shows how to use named colors, initialize custom colors, and apply color utilities like fade and tint. ```zig // Named colors (use directly) rl.clearBackground(.ray_white); rl.drawRectangle(10, 10, 100, 50, .red); // Custom color const custom = rl.Color.init(128, 64, 255, 255); // Color utilities const faded = rl.fade(.blue, 0.5); // 50% transparent blue const tinted = color.tint(.red); // Apply tint ``` -------------------------------- ### Dynamic Bit Set Initialization and Resizing Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-bit-set.md Shows how to initialize a DynamicBitSet with an allocator, set bits, and dynamically resize the set. It also demonstrates cloning a DynamicBitSet. ```zig var bits = try std.DynamicBitSet.initEmpty(allocator, 1000); defer bits.deinit(); bits.set(42); bits.set(100); // Resize dynamically try bits.resize(2000, false); // false = new bits are 0 try bits.resize(2000, true); // true = new bits are 1 // Clone var copy = try bits.clone(allocator); defer copy.deinit() ``` -------------------------------- ### Link System and Static Libraries Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Demonstrates linking system libraries like 'pthread' and 'ssl', adding static library files, and setting library search paths. It also shows how to explicitly link libc and libcpp. ```zig // System library exe.root_module.linkSystemLibrary("pthread", .{}); exe.root_module.linkSystemLibrary("ssl", .{}); // Static library file exe.addObjectFile(b.path("lib/libfoo.a")); // Library search path exe.addLibraryPath(b.path("lib")); exe.addRPath(b.path("lib")); // Link libc (set via createModule options or directly) exe.root_module.link_libc = true; exe.root_module.link_libcpp = true; ``` -------------------------------- ### Install Artifacts to Default Location Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-build.md Installs executable or library artifacts to their default locations within the Zig output directory (zig-out/bin or zig-out/lib). ```zig // Install to default location (zig-out/bin or zig-out/lib) b.installArtifact(exe); b.installArtifact(lib); ``` -------------------------------- ### Complete Example: Word Counter Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-array-hash-map.md A full example demonstrating how to use StringArrayHashMap to count word occurrences, printing the results in insertion order. ```zig const std = @import("std"); pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa.deinit(); var counts = std.StringArrayHashMap(u32).init(gpa.allocator()); defer counts.deinit(); const words = [_][]const u8{ "apple", "banana", "apple", "cherry", "banana", "apple" }; for (words) |word| { const result = try counts.getOrPut(word); if (result.found_existing) { result.value_ptr.* += 1; } else { result.value_ptr.* = 1; } } // Print in insertion order var it = counts.iterator(); while (it.next()) |entry| { std.debug.print("{s}: {}\n", .{ entry.key_ptr.*, entry.value_ptr.* }); } // Output (insertion order): // apple: 3 // banana: 2 // cherry: 1 } ``` -------------------------------- ### Get Font Metrics Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/ttf.md Retrieve various font metrics such as height, ascent, descent, and line skip. Also demonstrates how to get detailed glyph metrics for individual characters. ```zig // Get font height (line spacing) const height = font.getHeight(); // Get font ascent (baseline to top) const ascent = font.getAscent(); // Get font descent (baseline to bottom, negative) const descent = font.getDescent(); // Get recommended line skip const line_skip = font.getLineSkip(); // Get glyph metrics (returns struct directly, can error) const metrics = try font.getGlyphMetrics('W'); const min_x = metrics.minx; const max_x = metrics.maxx; const min_y = metrics.miny; const max_y = metrics.maxy; const advance = metrics.advance; ``` -------------------------------- ### Zig Fixed Buffer Allocator Setup Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/patterns.md Illustrates setting up a FixedBufferAllocator for scenarios without heap allocation, using a pre-defined buffer. ```zig var buffer: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buffer); const allocator = fba.allocator(); ``` -------------------------------- ### Basic SDL3 Initialization and Shutdown Pattern Source: https://github.com/rudedogg/zig-skills/blob/main/zig-sdl3-bindings/references/init-lifecycle.md Demonstrates the fundamental pattern for initializing required SDL3 subsystems and ensuring cleanup using `defer`. ```zig const sdl3 = @import("sdl3"); pub fn main() !void { // CRITICAL: Always call shutdown, even on error defer sdl3.shutdown(); // Initialize needed subsystems try sdl3.init(.{ .video = true, .audio = true }); defer sdl3.quit(.{ .video = true, .audio = true }); // ... your application code ... } ``` -------------------------------- ### Simple HTTP GET Request Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-net.md Function to perform a simple HTTP GET request to a given host and path. It constructs the HTTP request, sends it, and reads the response into an ArrayList. ```zig fn httpGet(allocator: Allocator, host: []const u8, path: []const u8) ![]u8 { const stream = try net.tcpConnectToHost(allocator, host, 80); defer stream.close(); var write_buf: [1024]u8 = undefined; var writer = stream.writer(&write_buf); const w = &writer.interface; try w.print("GET {s} HTTP/1.1\r\n", .{path}); try w.print("Host: {s}\r\n", .{host}); try w.writeAll("Connection: close\r\n\r\n"); try w.flush(); var read_buf: [4096]u8 = undefined; var reader = stream.reader(&read_buf); var response: std.ArrayList(u8) = .empty; defer response.deinit(allocator); while (true) { const chunk = reader.interface().take(4096) catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => return reader.getError().?, }; try response.appendSlice(allocator, chunk); } return response.toOwnedSlice(allocator); } ``` -------------------------------- ### Utility Functions for Enums Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-enums.md Shows utility functions for enums, including getting all values as a slice, safely getting the tag name, and safely converting an integer to an enum value. ```zig // Get all values as slice const colors = std.enums.values(Color); // [3]Color // Safe tag name (works with non-exhaustive) const name = std.enums.tagName(Color, .red); // "red" or null // Safe int-to-enum const maybe = std.enums.fromInt(Color, 1); // ?.green ``` -------------------------------- ### Creating Directories Source: https://github.com/rudedogg/zig-skills/blob/main/zig/references/std-fs.md Demonstrates how to create single directories, create nested directory structures, and create and open a directory simultaneously. ```APIDOC ## Creating Directories ### Description Creates new directories in the file system. ### Usage ```zig // Create single directory try std.fs.cwd().makeDir("new_dir"); // Create with all parents try std.fs.cwd().makePath("path/to/nested/dir"); // Create and open var dir = try std.fs.cwd().makeOpenPath("path/to/dir", .{}); defer dir.close(); ``` ```