move playAudio to frame

This commit is contained in:
Rokas Puzonas 2026-01-20 00:04:46 +02:00
parent e7e91f3cef
commit 4283dd9926
4 changed files with 47 additions and 20 deletions

View File

@ -11,6 +11,8 @@ pub const Data = @import("./data.zig").Data;
pub const Store = @import("./store.zig");
pub const Mixer = @import("./mixer.zig");
pub const Command = Mixer.Command;
const sokol = @import("sokol");
const saudio = sokol.audio;
@ -62,19 +64,6 @@ pub fn load(opts: Store.LoadOptions) !Data.Id {
return try store.load(opts);
}
pub const PlayOptions = struct {
id: Data.Id,
delay: f32 = 0
};
pub fn play(opts: PlayOptions) void {
mixer.queue(.{
.play = .{
.data_id = opts.id
}
});
}
fn sokolStreamCallback(buffer: [*c]f32, num_frames: i32, num_channels: i32) callconv(.c) void {
if (stopped) {
return;

View File

@ -4,6 +4,10 @@ const InputSystem = @import("./input.zig");
const KeyCode = InputSystem.KeyCode;
const Mouse = InputSystem.Mouse;
const AudioSystem = @import("./audio/root.zig");
const AudioData = AudioSystem.Data;
const AudioCommand = AudioSystem.Command;
pub const Nanoseconds = u64;
const Frame = @This();
@ -59,15 +63,34 @@ pub const KeyState = struct {
}
};
pub const Audio = struct {
commands: std.ArrayList(AudioCommand),
pub const empty = Audio{
.commands = .empty
};
};
arena: std.heap.ArenaAllocator,
time_ns: Nanoseconds,
dt_ns: Nanoseconds,
input: Input,
audio: Audio,
pub const empty = Frame{
pub fn init(gpa: std.mem.Allocator) Frame {
return Frame{
.arena = std.heap.ArenaAllocator.init(gpa),
.time_ns = 0,
.dt_ns = 0,
.input = .empty
};
.input = .empty,
.audio = .empty
};
}
pub fn deinit(self: *Frame) void {
self.arena.deinit();
}
pub fn deltaTime(self: Frame) f32 {
return @as(f32, @floatFromInt(self.dt_ns)) / std.time.ns_per_s;
@ -104,3 +127,15 @@ pub fn getKeyState(self: Frame, key_code: KeyCode) KeyState {
.down_duration = self.getKeyDownDuration(key_code)
};
}
pub const PlayAudioOptions = struct {
id: AudioData.Id,
};
pub fn playAudio(self: *Frame, options: PlayAudioOptions) !void {
try self.audio.commands.append(self.arena.allocator(), .{
.play = .{
.data_id = options.id
}
});
}

View File

@ -52,7 +52,7 @@ pub fn run(self: *Engine, opts: RunOptions) !void {
.last_frame_at = 0,
.assets = undefined,
.game = undefined,
.frame = .empty
.frame = undefined
};
var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
@ -67,6 +67,8 @@ pub fn run(self: *Engine, opts: RunOptions) !void {
self.allocator = std.heap.smp_allocator;
}
self.frame = .init(self.allocator);
tracy.setThreadName("Main");
if (builtin.os.tag == .linux) {
@ -135,6 +137,7 @@ fn sokolCleanup(self: *Engine) void {
const zone = tracy.initZone(@src(), .{ });
defer zone.deinit();
self.frame.deinit();
Audio.deinit();
self.game.deinit();
self.assets.deinit(self.allocator);

View File

@ -51,7 +51,7 @@ pub fn tick(self: *Game, frame: *Engine.Frame) !void {
dir = dir.normalized();
if (dir.x != 0 or dir.y != 0) {
Audio.play(.{
try frame.playAudio(.{
.id = self.assets.wood01
});
}