Compare commits

..

No commits in common. "8097ff725b9bf027c6ab1ceabf1f34ee50e36df1" and "a99bf9c17b9e750ac706571a5b5c0f5e73e98044" have entirely different histories.

16 changed files with 400 additions and 1251 deletions

View File

@ -1,23 +0,0 @@
Impact Sounds (1.0)
Created/distributed by Kenney (www.kenney.nl)
Creation date: 19-12-2019
------------------------------
License: (Creative Commons Zero, CC0)
http://creativecommons.org/publicdomain/zero/1.0/
This content is free to use in personal, educational and commercial projects.
Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
------------------------------
Donate: http://support.kenney.nl
Request: http://request.kenney.nl
Patreon: http://patreon.com/kenney/
Follow on Twitter for updates:
http://twitter.com/KenneyNL

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.12.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="64" tileheight="64" infinite="0" nextlayerid="6" nextobjectid="4">
<map version="1.10" tiledversion="1.12.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="64" tileheight="64" infinite="0" nextlayerid="5" nextobjectid="1">
<tileset firstgid="1" source="tileset.tsx"/>
<layer id="2" name="Ground" width="30" height="20">
<data encoding="csv">
@ -49,7 +49,7 @@
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
</data>
</layer>
<layer id="4" name="Boxes" width="30" height="20">
<layer id="4" name="Pushable" width="30" height="20">
<data encoding="csv">
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
@ -73,9 +73,4 @@
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
</data>
</layer>
<objectgroup id="5" name="Markers">
<object id="1" name="spawn" x="479" y="550">
<point/>
</object>
</objectgroup>
</map>

View File

@ -1,31 +1,17 @@
{
"activeFile": "map.tmx",
"activeFile": "",
"expandedProjectPaths": [
],
"file.lastUsedOpenFilter": "All Files (*)",
"fileStates": {
"map.tmx": {
"scale": 1,
"selectedLayer": 3,
"viewCenter": {
"x": 624.5,
"y": 421
}
},
"tileset.tsx": {
"scaleInDock": 1
}
},
"last.imagePath": "/home/rokas/code/games/sokol-template-v2/assets/sokoban",
"map.lastUsedFormat": "tmx",
"map.tileHeight": 64,
"map.tileWidth": 64,
"openFiles": [
"map.tmx"
],
"project": "sokoban.tiled-project",
"recentFiles": [
"map.tmx"
],
"tileset.lastUsedFormat": "tsx",
"tileset.tileSize": {

View File

@ -10,8 +10,7 @@ pub fn build(b: *std.Build) !void {
"sokoban/sokoban_tilesheet.png",
"roboto-font/Roboto-Regular.ttf",
"tiled/map.tmx",
"tiled/tileset.tsx",
"impact-sounds/footstep_concrete_000.ogg"
"tiled/tileset.tsx"
};
const asset_dir_realpath = try b.build_root.join(b.graph.arena, &.{ assets_dir });

View File

@ -98,16 +98,7 @@ pub const ObjectVariant = struct {
color: ?Color,
draw_order: DrawOrder,
items: []Object,
pub fn getByName(self: *const ObjectVariant, name: []const u8) ?*const Object {
for (self.items) |*item| {
if (std.mem.eql(u8, item.name, name)) {
return item;
}
}
return null;
}
items: []Object
};
pub const GroupVariant = struct {

View File

@ -77,14 +77,6 @@ pub const Tile = struct {
pub fn getProperties(self: Tile) Property.List {
return self.tileset.getTileProperties(self.id) orelse .empty;
}
pub fn getPositionInImage(self: Tile) Position {
return self.tileset.getTilePositionInImage(self.id);
}
pub fn getPosition(self: Tile) Tileset.TilePosition {
return self.tileset.getTilePosition(self.id);
}
};
arena: std.heap.ArenaAllocator,
@ -238,72 +230,6 @@ pub fn getTile(self: *const Tilemap, layer: *const Layer, tilesets: Tileset.List
};
}
pub fn getLayer(self: *const Tilemap, name: []const u8) ?*const Layer {
for (self.layers) |*layer| {
if (std.mem.eql(u8, layer.name, name)) {
return layer;
}
}
return null;
}
pub const Bounds = struct {
min_x: usize,
min_y: usize,
max_x: usize,
max_y: usize,
const zero = Bounds{
.min_x = 0,
.min_y = 0,
.max_x = 0,
.max_y = 0,
};
pub fn width(self: Bounds) usize {
return self.max_x - self.min_x + 1;
}
pub fn height(self: Bounds) usize {
return self.max_y - self.min_y + 1;
}
};
pub fn getTileBounds(self: *const Tilemap) Bounds {
var result: ?Bounds = null;
for (self.layers) |*layer| {
if (layer.variant != .tile) {
continue;
}
for (0..self.height) |y| {
for (0..self.width) |x| {
const gid = layer.variant.tile.get(x, y).?;
if (gid != 0) {
if (result) |bounds| {
result = Bounds{
.min_x = @min(x, bounds.min_x),
.min_y = @min(y, bounds.min_y),
.max_x = @max(x, bounds.max_x),
.max_y = @max(y, bounds.max_y)
};
} else {
result = Bounds{
.min_x = x,
.min_y = y,
.max_x = x,
.max_y = y
};
}
}
}
}
}
return result orelse Bounds.zero;
}
pub fn deinit(self: *const Tilemap) void {
self.arena.deinit();
}

View File

@ -1,6 +1,5 @@
const std = @import("std");
const Io = std.Io;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const xml = @import("./xml.zig");
@ -205,32 +204,21 @@ pub fn getTileProperties(self: *const Tileset, id: u32) ?Property.List {
return null;
}
pub const TilePosition = struct {
x: usize,
y: usize,
};
pub fn getTilePosition(self: *const Tileset, id: u32) TilePosition {
assert(id < self.tile_count);
pub fn getTilePositionInImage(self: *const Tileset, id: u32) ?Position {
if (id >= self.tile_count) {
return null;
}
const tileset_width = @divExact(self.image.width, self.tile_width);
const tile_x = @mod(id, tileset_width);
const tile_y = @divFloor(id, tileset_width);
return .{
.x = tile_x,
.y = tile_y,
};
}
pub fn getTilePositionInImage(self: *const Tileset, id: u32) Position {
const pos = self.getTilePosition(id);
return Position{
.x = @floatFromInt(pos.x * self.tile_width),
.y = @floatFromInt(pos.y * self.tile_height),
.x = @floatFromInt(tile_x * self.tile_width),
.y = @floatFromInt(tile_y * self.tile_height),
};
}
pub fn deinit(self: *const Tileset) void {

View File

@ -1,6 +1,5 @@
const std = @import("std");
const log = std.log.scoped(.app);
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Math = @import("math");
@ -41,75 +40,20 @@ const PlayerSprites = struct {
}
};
const Tilemap = struct {
tiles: []Tile,
width: usize,
height: usize,
const Tile = struct {
ground_sprite: ?Gfx.Sprite.Id,
wall_sprite: ?Gfx.Sprite.Id,
const empty = Tile{
.ground_sprite = null,
.wall_sprite = null
};
};
pub fn init(gpa: Allocator, width: usize, height: usize) !Tilemap {
const tiles = try gpa.alloc(Tile, width * height);
@memset(tiles, .empty);
return Tilemap{
.width = width,
.height = height,
.tiles = tiles
};
}
pub fn deinit(self: *Tilemap, gpa: Allocator) void {
gpa.free(self.tiles);
}
pub fn get(self: *Tilemap, x: usize, y: usize) *Tile {
assert(x < self.width);
assert(y < self.height);
return &self.tiles[y * self.width + x];
}
};
const Entity = struct {
type: Type,
pos_x: i32 = 0,
pos_y: i32 = 0,
sprite: ?Gfx.Sprite.Id = null,
player_direction: Direction = .down,
player_frame_index: u32 = 0,
const Type = enum {
player,
box
};
const SlotMap = Platform.SlotMapType(u8, u16, Entity);
const Id = SlotMap.Id;
};
show_first_window: bool,
check: bool,
player_pos: Vec2,
wall_sprite: Gfx.Sprite.Id,
roboto_font: Gfx.Font.Id,
tilemap: Tilemap,
entities: Entity.SlotMap,
tilesheet: Tilesheet,
player_sprites: PlayerSprites,
player_direction: Direction,
player_frame_index: u32,
animation_timer: Platform.Nanoseconds,
footstep_buffer: Audio.BufferId,
footstep_sound: Audio.SoundId = .nil,
sfx_bus: Audio.BusId,
sound: Audio.Sound.Id,
const Tilesheet = struct {
image: Gfx.ImageData,
@ -118,9 +62,7 @@ const Tilesheet = struct {
width: u32,
height: u32,
pub fn init(gpa: Allocator, image: Gfx.ImageData, tile_width: u32, tile_height: u32) !Tilesheet {
const width = image.width / tile_width;
const height = image.height / tile_height;
pub fn init(gpa: Allocator, image: Gfx.ImageData, width: u32, height: u32, tile_size: Vec2) !Tilesheet {
const sprites = try gpa.alloc(Gfx.Sprite.Id, width * height);
errdefer gpa.free(sprites);
@memset(sprites, .nil);
@ -130,7 +72,7 @@ const Tilesheet = struct {
.image = image,
.width = width,
.height = height,
.tile_size = .initFromInt(u32, tile_width, tile_height)
.tile_size = tile_size
};
}
@ -140,7 +82,7 @@ const Tilesheet = struct {
}
}
pub fn get(self: Tilesheet, x: usize, y: usize) Gfx.Sprite.Id {
pub fn get(self: Tilesheet, x: u32, y: u32) Gfx.Sprite.Id {
if (x >= self.width or y >= self.height) {
log.warn("Attempt to get tile which is out of bounds", .{});
return .nil;
@ -164,6 +106,24 @@ pub fn init(self: *App, plt: Platform.Init) !?u8 {
const robot_font = Gfx.initFont();
Gfx.setFont(robot_font, plt.assets.readFile("roboto-font/Roboto-Regular.ttf"));
var scratch = std.heap.ArenaAllocator.init(plt.gpa);
defer scratch.deinit();
var buffers = Tiled.xml.Lexer.Buffers.init(plt.gpa);
defer buffers.deinit();
const tilemap = try Tiled.Tilemap.initFromBuffer(plt.gpa, &scratch, &buffers, plt.assets.readFile("tiled/map.tmx"));
defer tilemap.deinit();
var tilesets: Tiled.Tileset.List = .empty;
defer tilesets.deinit(plt.gpa);
try tilesets.add(plt.gpa, "tiled/tilemap.tsx", try Tiled.Tileset.initFromBuffer(plt.gpa, &scratch, &buffers, plt.assets.readFile("tiled/tileset.tsx")));
for (tilemap.layers) |layer| {
std.debug.print("{s}\n", .{layer.name});
}
const tilesheet_png = try STBImage.load(plt.assets.readFile("sokoban/sokoban_tilesheet.png"));
const tilesheet = try Tilesheet.init(
plt.arena,
@ -172,9 +132,13 @@ pub fn init(self: *App, plt: Platform.Init) !?u8 {
.height = tilesheet_png.height,
.pixels = .{ .rgba8 = tilesheet_png.rgba8_pixels }
},
64, 64,
13,
8,
.init(64, 64)
);
const wall_sprite = tilesheet.get(1, 0);
var player_sprites: PlayerSprites = undefined;
inline for (.{
.{
@ -200,203 +164,99 @@ pub fn init(self: *App, plt: Platform.Init) !?u8 {
}
}
const footstep_sound = Audio.addBuffer(.{
.vorbis = plt.assets.readFile("impact-sounds/footstep_concrete_000.ogg")
const sound = Audio.initSound(.{
.cb = .{ .sample = sinSampleCallback },
.playing = false,
.frequency = 1
});
self.* = App{
.player_pos = .init(100, 100),
.show_first_window = true,
.check = false,
.player_sprites = player_sprites,
.wall_sprite = wall_sprite,
.roboto_font = robot_font,
.player_direction = .left,
.player_frame_index = 0,
.animation_timer = 0,
.tilesheet = tilesheet,
.footstep_buffer = footstep_sound,
.sfx_bus = Audio.addBus(.{ .label = "sfx" }),
.tilemap = undefined,
.entities = try .initCapacity(plt.gpa, 256)
.sound = sound
};
var player_pos_x: i32 = 0;
var player_pos_y: i32 = 0;
{
var scratch = std.heap.ArenaAllocator.init(plt.gpa);
defer scratch.deinit();
var buffers = Tiled.xml.Lexer.Buffers.init(plt.gpa);
defer buffers.deinit();
const tilemap = try Tiled.Tilemap.initFromBuffer(plt.gpa, &scratch, &buffers, plt.assets.readFile("tiled/map.tmx"));
defer tilemap.deinit();
var tilesets: Tiled.Tileset.List = .empty;
defer tilesets.deinit(plt.gpa);
try tilesets.add(plt.gpa, "tileset.tsx", try Tiled.Tileset.initFromBuffer(plt.gpa, &scratch, &buffers, plt.assets.readFile("tiled/tileset.tsx")));
const bounds = tilemap.getTileBounds();
self.tilemap = try Tilemap.init(plt.gpa, bounds.width(), bounds.height());
const ground = tilemap.getLayer("Ground").?;
const walls = tilemap.getLayer("Walls").?;
for (0..bounds.height()) |oy| {
for (0..bounds.width()) |ox| {
const x = bounds.min_x + ox;
const y = bounds.min_y + oy;
const tile = self.tilemap.get(ox, oy);
if (tilemap.getTile(ground, tilesets, x, y)) |tiled_tile| {
const pos = tiled_tile.getPosition();
tile.ground_sprite = tilesheet.get(pos.x, pos.y);
}
if (tilemap.getTile(walls, tilesets, x, y)) |tiled_tile| {
const pos = tiled_tile.getPosition();
tile.wall_sprite = tilesheet.get(pos.x, pos.y);
}
}
}
const markers = &tilemap.getLayer("Markers").?.variant.object;
const spawn = markers.getByName("spawn").?;
player_pos_x = @divFloor(@as(i32, @intFromFloat(spawn.shape.point.x)), @as(i32, @intCast(tilemap.tile_width)));
player_pos_x -= @intCast(bounds.min_x);
player_pos_y = @divFloor(@as(i32, @intFromFloat(spawn.shape.point.y)),@as(i32, @intCast(tilemap.tile_height)));
player_pos_y -= @intCast(bounds.min_y);
const boxes = tilemap.getLayer("Boxes").?;
for (0..bounds.height()) |oy| {
for (0..bounds.width()) |ox| {
const x = bounds.min_x + ox;
const y = bounds.min_y + oy;
if (tilemap.getTile(boxes, tilesets, x, y)) |tiled_tile| {
const pos = tiled_tile.getPosition();
_ = try self.spawnBox(@intCast(ox), @intCast(oy), tilesheet.get(pos.x, pos.y));
}
}
}
}
const player_id = try self.spawnPlayer();
const player = self.entities.getAssumeExists(player_id);
player.pos_x = player_pos_x;
player.pos_y = player_pos_y;
return null;
}
fn spawnPlayer(self: *App) !Entity.Id {
return try self.entities.insert(Entity{
.type = .player,
});
}
fn spawnBox(self: *App, x: i32, y: i32, sprite: Gfx.Sprite.Id) !Entity.Id {
return try self.entities.insert(Entity{
.type = .box,
.pos_x = x,
.pos_y = y,
.sprite = sprite
});
fn sinSampleCallback(sound: *Audio.Sound) f32 {
return @sin(440 * sound.phase);
}
pub fn frame(self: *App, plt: Platform.Frame) !void {
const input = plt.input;
var dir_y: i32 = 0;
var dir_x: i32 = 0;
if (input.isKeyPressedOrRepeat(.S)) {
dir_y += 1;
const dt = plt.deltaTime();
var dir: Vec2 = .init(0, 0);
if (input.isKeyDown(.S)) {
dir.y += 1;
}
if (input.isKeyPressedOrRepeat(.W)) {
dir_y -= 1;
if (input.isKeyDown(.W)) {
dir.y -= 1;
}
if (input.isKeyPressedOrRepeat(.D)) {
dir_x += 1;
if (input.isKeyDown(.D)) {
dir.x += 1;
}
if (input.isKeyPressedOrRepeat(.A)) {
dir_x -= 1;
if (input.isKeyDown(.A)) {
dir.x -= 1;
}
if (dir_x != 0) {
dir_y = 0;
dir = dir.normalized();
self.player_pos = self.player_pos.add(dir.multiplyScalar(50 * dt));
if (input.isKeyPressed(.E)) {
Audio.setPlaying(self.sound, !Audio.getPlaying(self.sound));
}
Gfx.setClearColor(.rgb(40, 40, 40));
const tile_size = Vec2.init(48, 48);
for (0..self.tilemap.height) |y| {
for (0..self.tilemap.width) |x| {
const tile = self.tilemap.get(x, y);
if (tile.ground_sprite) |sprite| {
Gfx.drawSprite(sprite, Vec2.initFromInt(usize, x, y).multiply(tile_size), tile_size, .white);
}
if (tile.wall_sprite) |sprite| {
Gfx.drawSprite(sprite, Vec2.initFromInt(usize, x, y).multiply(tile_size), tile_size, .white);
}
}
}
var entity_iter = self.entities.iterator();
while (entity_iter.next()) |entity_id| {
const entity = self.entities.getAssumeExists(entity_id);
if (entity.type == .player) {
entity.pos_x += dir_x;
entity.pos_y += dir_y;
var new_direction = entity.player_direction;
if (dir_x < 0) {
var new_direction = self.player_direction;
if (dir.x < 0) {
new_direction = .left;
} else if (dir_x > 0) {
} else if (dir.x > 0) {
new_direction = .right;
} else if (dir_y > 0) {
} else if (dir.y > 0) {
new_direction = .down;
} else if (dir_y < 0) {
} else if (dir.y < 0) {
new_direction = .up;
}
if (entity.player_direction != new_direction) {
entity.player_frame_index = 0;
entity.player_direction = new_direction;
if (self.player_direction != new_direction) {
self.player_frame_index = 0;
self.player_direction = new_direction;
}
const frames = self.player_sprites.getDirection(entity.player_direction);
const frames = self.player_sprites.getDirection(self.player_direction);
if (dir_x != 0 or dir_y != 0) {
self.animation_timer += plt.input.delta_time;
if (dir.x != 0 or dir.y != 0) {
self.animation_timer += plt.dt;
const animatin_time = std.time.ns_per_s / 5;
while (self.animation_timer >= animatin_time) {
entity.player_frame_index = (entity.player_frame_index + 1) % @as(u32, @intCast(frames.len));
self.player_frame_index = (self.player_frame_index + 1) % @as(u32, @intCast(frames.len));
self.animation_timer -= animatin_time;
}
} else {
self.animation_timer = 0;
entity.player_frame_index = 0;
}
if (dir_x != 0 or dir_y != 0) {
self.footstep_sound = Audio.play(.{ .buffer = self.footstep_buffer, .bus = self.sfx_bus });
}
entity.sprite = frames[entity.player_frame_index];
}
if (entity.sprite) |sprite| {
Gfx.drawSprite(
sprite,
Vec2.initFromInt(i32, entity.pos_x, entity.pos_y).multiply(tile_size),
tile_size,
.white
);
}
self.player_frame_index = 0;
}
Gfx.setClearColor(.rgb(40, 40, 40));
Gfx.drawSprite(frames[self.player_frame_index], self.player_pos, .init(64, 64), .white);
Gfx.drawSprite(self.tilesheet.get(11, 6), self.player_pos.add(.init(0, 200)), .init(64, 64), .white);
Gfx.drawText(self.roboto_font, .{
.pos = .init(300, 100),
.text = "Hello, World!",
.height = 64,
});
}
pub fn deinit(self: *App, plt: Platform.Deinit) void {
self.tilemap.deinit(plt.gpa);
self.entities.slots.deinit(plt.gpa);
_ = plt; // autofix
_ = self; // autofix
}

View File

@ -1,66 +1,47 @@
const std = @import("std");
const log = std.log.scoped(.audio);
const Io = std.Io;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const build_options = @import("build_options");
const sokol = @import("sokol");
const sapp = sokol.app;
const saudio = sokol.audio;
const ImGUI = @import("imgui.zig");
const tracy = @import("tracy");
const STBVorbis = @import("stb_vorbis");
const Math = @import("math");
const SlotMapType = @import("./slot_map.zig").SlotMapType;
const Bus = struct {
label: ?[]const u8 = null,
volume: f32 = 1,
parent_id: ?Bus.Id = null,
const State = struct {
io: Io,
mutex: std.Io.Mutex,
sounds: Sound.SlotMap,
volume: f32 = 0.1,
running: std.atomic.Value(bool) = .init(false),
pub const Id = packed struct {
index: u16,
pub const nil = Id{ .index = std.math.maxInt(u16) };
};
};
pub const BusId = Bus.Id;
const Buffer = struct {
samples: Samples,
const Samples = struct {
len: usize,
left: [*]const f32,
// If `right` is is null, then this is mono
right: ?[*]const f32,
pub fn deinit(self: Samples, gpa: Allocator) void {
gpa.free(self.left[0..self.len]);
if (self.right) |right| {
gpa.free(right[0..self.len]);
}
}
temp_buffer: []f32
};
pub const Id = packed struct {
index: u16,
var g_state: State = undefined;
pub const nil = Id{ .index = std.math.maxInt(u16) };
pub const InitOptions = struct {
logger: saudio.Logger = .{},
buffer_frames: u32 = 512,
max_sounds: usize = 128,
};
};
pub const BufferId = Buffer.Id;
const Sound = struct {
cursor: usize,
buffer: BufferId,
volume: f32 = 1,
loop: bool = false,
bus: BusId,
pub const Sound = struct {
cb: Callback,
userdata: ?*anyopaque,
volume: f32,
looping: bool,
adsr: ADSR,
playing: bool,
phase_increment: f32 = 0,
duration_frames: u32 = 0,
frame_index: u32 = 0,
phase: f32 = 0,
pub const ADSR = struct {
attack: f32,
@ -68,7 +49,7 @@ const Sound = struct {
sustain: f32,
release: f32,
pub const identity = ADSR{
pub const default = ADSR{
.attack = 0,
.decay = 0,
.sustain = 1,
@ -76,544 +57,195 @@ const Sound = struct {
};
};
const SlotMap = SlotMapType(u16, u8, Sound);
const Id = SlotMap.Id;
};
pub const SoundId = Sound.Id;
const ThreadState = struct {
// When modifying any fields in this struct, you must first acquire the mutex.
mutex: std.Io.Mutex,
sounds: Sound.SlotMap,
bus_volumes: []f32,
elapsed_time_ms: ?[]f32 = null,
budget_reached_counter: u32 = 0
pub const Callback = union(enum) {
sample: *const fn(sound: *Sound) f32,
block: *const fn(sound: *Sound, samples: *std.ArrayList(f32)) void,
};
const State = struct {
io: Io,
gpa: Allocator,
running: std.atomic.Value(bool) = .init(false),
vorbis_alloc_buffer: []u8,
buses: std.ArrayList(Bus),
buffers: std.ArrayList(Buffer),
thread_state: ThreadState
};
var g_state: State = undefined;
pub var main_bus: BusId = .nil;
const g_sample_rate = 44100;
pub const InitOptions = struct {
logger: saudio.Logger = .{},
buffer_frames: u32 = 512,
max_buffers: usize = 128,
max_sounds: usize = 256,
max_buses: usize = 16,
max_vorbis_alloc_buffer_size: u32 = 1 * Math.bytes_per_mib,
track_elapsed_time: bool = build_options.has_imgui
const SlotMap = SlotMapType(u8, u16, Sound);
pub const Id = SlotMap.Id;
};
pub fn init(io: Io, gpa: std.mem.Allocator, opts: InitOptions) !void {
const channels = 1; // TODO: Stereo audio
const self = &g_state;
var buses = try std.ArrayList(Bus).initCapacity(gpa, opts.max_buses);
errdefer buses.deinit(gpa);
const sounds_buffer = try gpa.alloc(Sound.SlotMap.Slot, opts.max_sounds);
errdefer gpa.free(sounds_buffer);
const bus_volumes = try gpa.alloc(f32, opts.max_buses);
errdefer gpa.free(bus_volumes);
var buffers = try std.ArrayList(Buffer).initCapacity(gpa, opts.max_buffers);
errdefer buffers.deinit(gpa);
const sounds = try gpa.alloc(Sound.SlotMap.Slot, opts.max_sounds);
errdefer gpa.free(sounds);
const vorbis_alloc_buffer = try gpa.alloc(u8, opts.max_vorbis_alloc_buffer_size);
errdefer gpa.free(vorbis_alloc_buffer);
const temp_buffer = try gpa.alloc(f32, opts.buffer_frames);
errdefer gpa.free(temp_buffer);
self.* = State{
.io = io,
.gpa = gpa,
.buffers = buffers,
.buses = buses,
.vorbis_alloc_buffer = vorbis_alloc_buffer,
.thread_state = .{
.mutex = .init,
.sounds = .initBuffer(sounds),
.bus_volumes = bus_volumes,
}
.sounds = .init(sounds_buffer),
.temp_buffer = temp_buffer,
};
self.running.store(true, .seq_cst);
main_bus = addBus(.{
.label = "main"
});
const channels = 2;
saudio.setup(.{
.stream_cb = sokolStreamCallback,
.logger = opts.logger,
.num_channels = channels,
.buffer_frames = @intCast(opts.buffer_frames),
.sample_rate = g_sample_rate
});
if (opts.track_elapsed_time) {
const measurements_per_second: usize = @intCast(@divFloor(std.time.ns_per_s, getMaxAudioThreadDuration().nanoseconds));
self.thread_state.elapsed_time_ms = try gpa.alloc(f32, 3*measurements_per_second);
@memset(self.thread_state.elapsed_time_ms.?, 0);
}
self.running.store(true, .seq_cst);
log.debug("Init:", .{});
log.debug("- sample_rate: {}", .{saudio.sampleRate()});
log.debug("- channels: {}", .{saudio.channels()});
log.debug("- buffer_frames: {}", .{saudio.bufferFrames()});
}
pub fn deinit(gpa: std.mem.Allocator) void {
var self = &g_state;
{
self.thread_state.mutex.lock(self.io) catch @panic("Failed to lock audio mutex");
defer self.thread_state.mutex.unlock(self.io);
self.running.store(false, .seq_cst);
}
saudio.shutdown();
for (self.buffers.items) |buffer| {
buffer.samples.deinit(gpa);
}
self.buffers.deinit(gpa);
self.buses.deinit(gpa);
gpa.free(self.thread_state.sounds.slots.allocatedSlice());
gpa.free(self.thread_state.bus_volumes);
if (self.thread_state.elapsed_time_ms) |elapsed_time_ms| {
gpa.free(elapsed_time_ms);
}
gpa.free(self.vorbis_alloc_buffer);
gpa.free(self.sounds.slots.allocatedSlice());
gpa.free(self.temp_buffer);
}
const BufferData = union(enum) {
raw: struct {
samples_mono: []f32,
sample_rate: u32
},
vorbis: []const u8
};
// Source: https://amini-allight.org/post/game-audio-programming-tutorial-part-6
fn hermiteResample(input: []f32, output: []f32) void {
for (0..output.len) |i| {
const elapsed = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(output.len));
const b_index: isize = @intFromFloat(elapsed * @as(f32, @floatFromInt(input.len)));
const a_index = b_index - 1;
const c_index = b_index + 1;
const d_index = b_index + 2;
const a = if (a_index >= 0 and a_index < input.len) input[@intCast(a_index)] else input[@intCast(b_index)];
const b = input[@intCast(b_index)];
const c = if (c_index >= 0 and c_index < input.len) input[@intCast(c_index)] else input[@intCast(b_index)];
const d = if (d_index >= 0 and d_index < input.len) input[@intCast(d_index)] else input[@intCast(b_index)];
const t = (elapsed * @as(f32, @floatFromInt(input.len))) - @as(f32, @floatFromInt(b_index));
const c0 = b;
const c1 = (c - a) * 0.5;
const c2 = a - (b * 2.5) + (c * 2.0) - (d * 0.5);
const c3 = ((b - c) * 1.5) + ((d - a) * 0.5);
output[i] = (((((c3 * t) + c2) * t) + c1) * t) + c0;
}
pub fn getSampleRate() f32 {
return @floatFromInt(saudio.sampleRate());
}
fn resampleIfNeeded(gpa: Allocator, samples: *[]f32, sample_rate: u32) !void {
const new_sample_count = samples.len * g_sample_rate / sample_rate;
if (new_sample_count != samples.len) {
const new_samples = try gpa.alloc(f32, new_sample_count);
hermiteResample(samples.*, new_samples);
gpa.free(samples.*);
samples.* = new_samples;
}
}
fn bufferDataToSamples(data: BufferData) !Buffer.Samples {
const self = &g_state;
return switch (data) {
.raw => |raw| {
var samples = try self.gpa.dupe(f32, raw.samples_mono);
errdefer self.gpa.free(samples);
try resampleIfNeeded(self.gpa, &samples, raw.sample_rate);
return Buffer.Samples{
.len = samples.len,
.left = samples.ptr,
.right = null
};
},
.vorbis => |vorbis_data| {
const vorbis = try STBVorbis.init(vorbis_data, self.vorbis_alloc_buffer);
const sample_count = vorbis.getStreamLengthInSamples();
const info = vorbis.getInfo();
if (info.channels == 1) {
var samples = try self.gpa.alloc(f32, sample_count);
errdefer self.gpa.free(samples);
const result = vorbis.getSamples(&.{ samples.ptr }, sample_count);
assert(result == sample_count);
try resampleIfNeeded(self.gpa, &samples, info.sample_rate);
return .{
.len = samples.len,
.left = samples.ptr,
.right = null
};
} else if (info.channels >= 2) {
var left_samples = try self.gpa.alloc(f32, sample_count);
errdefer self.gpa.free(left_samples);
var right_samples = try self.gpa.alloc(f32, sample_count);
errdefer self.gpa.free(right_samples);
const result = vorbis.getSamples(&.{ left_samples.ptr, right_samples.ptr }, sample_count);
assert(result == sample_count);
try resampleIfNeeded(self.gpa, &left_samples, info.sample_rate);
try resampleIfNeeded(self.gpa, &right_samples, info.sample_rate);
return Buffer.Samples{
.len = left_samples.len,
.left = left_samples.ptr,
.right = right_samples.ptr
};
} else {
return Buffer.Samples{
.len = 0,
.left = &.{},
.right = null
};
}
}
};
}
pub fn addBuffer(data: BufferData) BufferId {
const self = &g_state;
if (self.buffers.items.len == self.buffers.capacity) {
log.warn("Max audio buffers reached, limit: {}", .{self.buffers.capacity});
return .nil;
}
const samples = bufferDataToSamples(data) catch |e| {
log.err("Failed to add buffer: {}", .{e});
return .nil;
};
const buffer_id = BufferId{ .index = @intCast(self.buffers.items.len) };
const buffer = self.buffers.addOneAssumeCapacity();
buffer.* = Buffer{
.samples = samples
};
assert(buffer_id != BufferId.nil);
return buffer_id;
}
pub fn addBus(opts: Bus) BusId {
const self = &g_state;
if (self.buses.items.len == self.buses.capacity) {
log.warn("Max audio buses reached, limit: {}", .{self.buses.capacity});
return .nil;
}
const bus_id = BusId{ .index = @intCast(self.buses.items.len) };
const bus = self.buses.addOneAssumeCapacity();
bus.* = opts;
if (bus.parent_id != null and bus.parent_id == BusId.nil) {
bus.parent_id = null;
}
if (bus.parent_id == null and main_bus != BusId.nil) {
bus.parent_id = main_bus;
}
assert(bus_id != BusId.nil);
return bus_id;
}
fn busMultipliedVolume(id: BusId) f32 {
const self = &g_state;
var result: f32 = 1;
var iter: ?BusId = id;
while (iter) |current| {
const bus = &self.buses.items[current.index];
result *= bus.volume;
iter = bus.parent_id;
}
return result;
}
const PlayOptions = struct {
buffer: BufferId,
// TODO: adsr: ?Sound.ADSR = null,
pub const SoundOptions = struct {
cb: Sound.Callback,
userdata: ?*anyopaque = null,
adsr: Sound.ADSR = .default,
volume: f32 = 1,
loop: bool = false,
bus: ?BusId = null
playing: bool = true,
looping: bool = false,
frequency: ?f32 = null,
duration_ns: ?u64 = null
};
pub fn play(opts: PlayOptions) SoundId {
const self = &g_state;
pub fn initSound(opts: SoundOptions) Sound.Id {
var self = &g_state;
var mutex = &self.thread_state.mutex;
var sounds = &self.thread_state.sounds;
self.mutex.lock(self.io) catch return .nil;
defer self.mutex.unlock(self.io);
mutex.lock(self.io) catch |e| {
log.warn("Failed to lock mutex: {}", .{e});
const id = self.sounds.insertUndefined() catch {
log.warn("Sound limit reached! limit: {}", .{self.sounds.slots.capacity});
return .nil;
};
defer mutex.unlock(self.io);
const bus = opts.bus orelse main_bus;
if (bus == BusId.nil) {
return .nil;
var phase_increment: f32 = 0;
if (opts.frequency) |frequency| {
phase_increment = frequency * 2 * std.math.pi / getSampleRate();
}
if (opts.buffer == BufferId.nil) {
return .nil;
var duration_frames: u32 = 0;
if (opts.duration_ns) |duration_ns| {
duration_frames = @intCast(duration_ns * @as(u64, @intCast(saudio.sampleRate())) / std.time.ns_per_s);
}
if (sounds.unusedCapacity() == 0) {
log.warn("Max sounds reached, limit: {}", .{sounds.slots.capacity});
return .nil;
}
const sound_id = sounds.insertAssumeCapacity();
const sound = sounds.getAssumeExists(sound_id);
const sound = self.sounds.getAssumeExists(id);
sound.* = Sound{
.cursor = 0,
.cb = opts.cb,
.userdata = opts.userdata,
.adsr = opts.adsr,
.looping = opts.looping,
.volume = opts.volume,
.loop = opts.loop,
.buffer = opts.buffer,
.bus = bus,
.playing = opts.playing,
.duration_frames = duration_frames,
.phase_increment = phase_increment
};
return sound_id;
return id;
}
pub fn stop(id: SoundId) void {
pub fn deinitSound(id: Sound.Id) void {
var self = &g_state;
if (self.sounds.get(id)) |sound| {
self.mutex.lock(self.io) catch return;
defer self.mutex.unlock(self.io);
_ = sound; // autofix
self.sounds.removeAssumeExists(id);
}
}
pub fn setPlaying(id: Sound.Id, playing: bool) void {
var self = &g_state;
if (self.sounds.get(id)) |sound| {
self.mutex.lock(self.io) catch return;
defer self.mutex.unlock(self.io);
sound.playing = playing;
}
}
pub fn getPlaying(id: Sound.Id) bool {
var self = &g_state;
if (self.sounds.get(id)) |sound| {
return sound.playing;
} else {
return false;
}
}
fn bumpSoundCursor(sound: *Sound, count: u32) void {
if (sound.duration_frames > 0) {
sound.frame_index += count;
sound.frame_index = @mod(sound.frame_index, sound.duration_frames);
}
if (sound.phase_increment > 0) {
sound.phase += sound.phase_increment * @as(f32, @floatFromInt(count));
sound.phase = @mod(sound.phase, 2 * std.math.pi);
}
}
fn sokolStream(buffer: [*c]f32, num_frames: u32, num_channels: u32) !void {
const self = &g_state;
var mutex = &self.thread_state.mutex;
var sounds = &self.thread_state.sounds;
mutex.lock(self.io) catch |e| {
log.warn("Failed to lock mutex: {}", .{e});
return;
};
defer mutex.unlock(self.io);
_ = sounds.remove(id);
}
pub fn getBus(id: BusId) ?*Bus {
const self = &g_state;
if (id == .nil) {
return null;
}
return &self.buses.items[id.index];
}
pub fn showDebug() void {
const self = &g_state;
const sounds = &self.thread_state.sounds;
const buses = &self.buses;
const buffers = &self.buffers;
_ = ImGUI.beginTabBar("audio tab bar");
defer ImGUI.endTabBar();
if (ImGUI.beginTabItem("General")) {
defer ImGUI.endTabItem();
ImGUI.text("Sample rate: {}Hz", .{saudio.sampleRate()});
ImGUI.text("Buffer frames: {}", .{saudio.bufferFrames()});
ImGUI.text("Max callback duration: {f}", .{getMaxAudioThreadDuration()});
ImGUI.separator();
ImGUI.text("Buffers: {}/{}", .{buffers.items.len, buffers.capacity});
ImGUI.text("Buses: {}/{}", .{buses.items.len, buses.capacity});
ImGUI.text("Sounds: {}/{}", .{sounds.count(), sounds.slots.capacity});
if (self.thread_state.elapsed_time_ms) |elapsed_time_ms| {
ImGUI.separator();
ImGUI.plotLines(.{
.label = "Elapsed (ms)",
.values = elapsed_time_ms,
.ex = .{
.scale_max = getMaxAudioThreadDurationMs()
}
});
var min_elapsed = elapsed_time_ms[0];
var max_elapsed = elapsed_time_ms[0];
var sum_elapsed = elapsed_time_ms[0];
for (elapsed_time_ms[1..]) |duration_ms| {
min_elapsed = @min(min_elapsed, duration_ms);
max_elapsed = @max(max_elapsed, duration_ms);
sum_elapsed += duration_ms;
}
const avg_elapsed = sum_elapsed / @as(f32, @floatFromInt(elapsed_time_ms.len));
ImGUI.text("Min/Max/Avg: {:.3}ms/{:.3}ms/{:.3}ms{s}", .{
min_elapsed, max_elapsed, avg_elapsed,
if (max_elapsed > getMaxAudioThreadDurationMs()) " !!!" else ""
});
}
ImGUI.separator();
ImGUI.text("Budget reached counter: {}", .{self.thread_state.budget_reached_counter});
}
if (ImGUI.beginTabItem("Buses")) {
defer ImGUI.endTabItem();
if(ImGUI.beginTable("buses", 3, 0)) {
defer ImGUI.endTable();
ImGUI.tableSetupColumn("ID (Label)", 0);
ImGUI.tableSetupColumn("Volume", 0);
ImGUI.tableSetupColumn("Multiplied volume", 0);
ImGUI.tableHeadersRow();
for (0.., buses.items) |i, *bus| {
ImGUI.pushID(.{ .int = @intCast(i) });
defer ImGUI.popID();
ImGUI.tableNextRow();
ImGUI.tableNextColumn();
ImGUI.text("{} ({s})", .{i, bus.label orelse "-"});
ImGUI.tableNextColumn();
_ = ImGUI.inputF32Drag(.{
.label = "",
.value = &bus.volume,
.ex = .{
.min = 0,
.max = 1,
.speed = 0.01
}
});
ImGUI.tableNextColumn();
ImGUI.text("{}", .{busMultipliedVolume(.{ .index = @intCast(i) })});
}
}
}
}
fn getMaxAudioThreadDuration() Io.Duration {
const margin = 0.05;
return Io.Duration{
.nanoseconds = @divFloor((@as(i64, @intFromFloat(@as(f64, @floatFromInt(std.time.ns_per_s)) * (1 - margin)))) * @as(i64, saudio.bufferFrames()), saudio.sampleRate())
};
}
fn getMaxAudioThreadDurationMs() f32 {
return @floatCast(@as(f64, @floatFromInt(getMaxAudioThreadDuration().nanoseconds)) / std.time.ns_per_ms);
}
fn sokolStream(output_buffer: [*c]f32, num_frames: u32, num_channels: u32) !void {
const self = &g_state;
const started_at = Io.Clock.awake.now(self.io);
var zone = tracy.initZone(@src(), .{});
defer zone.deinit();
const mutex = &self.thread_state.mutex;
const sounds = &self.thread_state.sounds;
const buses = self.buses.items;
const bus_volumes = self.thread_state.bus_volumes;
try mutex.lock(self.io);
defer mutex.unlock(self.io);
if (!self.running.load(.seq_cst)) {
return;
}
assert(num_channels == 2);
@memset(output_buffer[0..(num_frames*2)], 0);
try self.mutex.lock(self.io);
defer self.mutex.unlock(self.io);
for (0..buses.len) |i| {
bus_volumes[i] = busMultipliedVolume(.{ .index = @intCast(i) });
assert(num_channels == 1);
assert(self.temp_buffer.len >= num_frames);
@memset(buffer[0..num_frames], 0);
var iter = self.sounds.iterator();
while (iter.next()) |id| {
const sound = self.sounds.getAssumeExists(id);
if (!sound.playing) {
continue;
}
var sound_iter = sounds.iterator();
while (sound_iter.next()) |sound_id| {
const sound = sounds.getAssumeExists(sound_id);
const buffer = &self.buffers.items[sound.buffer.index];
const bus_id = sound.bus;
const bus = buses[bus_id.index];
_ = bus; // autofix
const volume = sound.volume * bus_volumes[bus_id.index];
const left_channel = buffer.samples.left;
const right_channel = buffer.samples.right orelse buffer.samples.left;
var output_index: usize = 0;
while (output_index < num_frames) {
while (sound.cursor < buffer.samples.len and output_index < num_frames) {
const left = left_channel[sound.cursor];
const right = right_channel[sound.cursor];
sound.cursor += 1;
output_buffer[2*output_index+0] += left * volume;
output_buffer[2*output_index+1] += right * volume;
output_index += 1;
}
if (!sound.loop) {
break;
} else {
if (sound.cursor == buffer.samples.len) {
sound.cursor = 0;
var samples = std.ArrayList(f32).initBuffer(self.temp_buffer[0..num_frames]);
switch (sound.cb) {
.block => |cb| {
cb(sound, &samples);
bumpSoundCursor(sound, @intCast(samples.items.len));
},
.sample => |cb| {
samples.expandToCapacity();
for (samples.items) |*sample| {
sample.* = cb(sound);
bumpSoundCursor(sound, 1);
}
}
}
if (!sound.loop and sound.cursor == buffer.samples.len) {
sounds.removeAssumeExists(sound_id);
for (0..samples.items.len) |i| {
buffer[i] += samples.items[i] * sound.volume * self.volume;
}
}
const duration = started_at.durationTo(Io.Clock.awake.now(self.io));
if (self.thread_state.elapsed_time_ms) |elapsed_time_ms| {
@memmove(elapsed_time_ms[1..elapsed_time_ms.len], elapsed_time_ms[0..(elapsed_time_ms.len-1)]);
elapsed_time_ms[0] = @floatCast(@as(f64, @floatFromInt(duration.nanoseconds)) / std.time.ns_per_ms);
}
if (duration.nanoseconds > getMaxAudioThreadDuration().nanoseconds) {
self.thread_state.budget_reached_counter += 1;
}
}
fn sokolStreamCallback(buffer: [*c]f32, num_frames_i32: i32, num_channels: i32) callconv(.c) void {

View File

@ -288,7 +288,7 @@ fn nextEvents(self: *FileWatcher) !?*File {
}
pub fn next(self: *FileWatcher, io: Io) !?[]const u8 {
const now = Io.Clock.awake.now(io);
const now = Io.Clock.real.now(io);
var queue_overflow = false;
while (true) {

View File

@ -168,16 +168,16 @@ pub fn init(gpa: std.mem.Allocator, logger: sg.Logger) !void {
.transforms = .initBuffer(&self.transforms_buffer),
.textures_buffer = undefined,
.textures = .initBuffer(&self.textures_buffer),
.textures = .init(&self.textures_buffer),
.sprites_buffer = undefined,
.sprites = .initBuffer(&self.sprites_buffer),
.sprites = .init(&self.sprites_buffer),
.spritesheets_buffer = undefined,
.spritesheets = .initBuffer(&self.spritesheets_buffer),
.spritesheets = .init(&self.spritesheets_buffer),
.fonts_buffer = undefined,
.fonts = .initBuffer(&self.fonts_buffer),
.fonts = .init(&self.fonts_buffer),
};
self.default_spritesheet = initSpritesheet(.{});
@ -233,6 +233,9 @@ pub fn init(gpa: std.mem.Allocator, logger: sg.Logger) !void {
}
});
}
repackSpritesheetIfNeeded(self.default_spritesheet);
rebuildSpritesheetTextureIfNeeded(self.default_spritesheet);
}
pub fn deinit() void {
@ -344,75 +347,45 @@ pub fn beginFrame() void {
.swapchain = sglue.swapchain()
});
self.bindings.views[shd.VIEW_tex].id = sg.invalid_id;
const default_spritesheet = self.spritesheets.getAssumeExists(self.default_spritesheet);
const spritesheet_texture = self.textures.getAssumeExists(default_spritesheet.texture);
self.bindings.views[shd.VIEW_tex] = spritesheet_texture.view;
self.bindings.samplers[shd.SMP_smp] = self.linear_sampler;
}
pub fn showDebug() void {
const self = &g_state;
_ = self; // autofix
_ = ImGUI.beginTabBar("graphics tab bar");
defer ImGUI.endTabBar();
// TODO: Improve this by using tables or somekind of filtering
if (ImGUI.beginTabItem("Spritesheets")) {
defer ImGUI.endTabItem();
if(ImGUI.beginTable("spritesheets", 2, 0)) {
defer ImGUI.endTable();
ImGUI.tableSetupColumn("ID", 0);
ImGUI.tableSetupColumn("Size", 0);
ImGUI.tableHeadersRow();
var spritesheet_iter = self.spritesheets.iterator();
while (spritesheet_iter.next()) |spritesheet_id| {
const spritesheet = self.spritesheets.getAssumeExists(spritesheet_id);
ImGUI.pushID(.{ .int = spritesheet_id.index });
defer ImGUI.popID();
ImGUI.tableNextRow();
ImGUI.tableNextColumn();
ImGUI.text("{{ {}, {} }}", .{spritesheet_id.index, spritesheet_id.generation});
ImGUI.tableNextColumn();
ImGUI.text("{}x{}", .{spritesheet.size.x, spritesheet.size.x});
}
}
}
if (ImGUI.beginTabItem("Sprites")) {
defer ImGUI.endTabItem();
if(ImGUI.beginTable("sprites", 2, 0)) {
defer ImGUI.endTable();
ImGUI.tableSetupColumn("ID", 0);
ImGUI.tableSetupColumn("Position", 0);
ImGUI.tableHeadersRow();
var sprite_iter = self.sprites.iterator();
while (sprite_iter.next()) |sprite_id| {
const sprite = self.sprites.getAssumeExists(sprite_id);
ImGUI.pushID(.{ .int = sprite_id.index });
defer ImGUI.popID();
ImGUI.tableNextRow();
ImGUI.tableNextColumn();
ImGUI.text("{{ {}, {} }}", .{sprite_id.index, sprite_id.generation});
ImGUI.tableNextColumn();
if (sprite.position) |position| {
ImGUI.text("{:3}, {:3}", .{position.x, position.y});
} else {
ImGUI.text("null", .{});
}
}
}
}
// if (ImGUI.beginWindow(.{
// .name = "graphics",
// .size = .init(200, 200)
// })) {
// defer ImGUI.endWindow();
//
// {
// ImGUI.text("Spritesheets:", .{});
// var spritesheet_iter = self.spritesheets.iterator();
// while (spritesheet_iter.next()) |spritesheet_id| {
// const spritesheet = self.spritesheets.getAssumeExists(spritesheet_id);
// const texture = self.textures.get(spritesheet.texture);
// ImGUI.text("{f}:", .{spritesheet_id});
// ImGUI.text(" - needs_texture_rebuild:{}", .{spritesheet.needs_texture_rebuild});
// ImGUI.text(" - texture:{?}", .{texture});
// }
// }
//
// {
// ImGUI.text("Sprites:", .{});
// var sprite_iter = self.sprites.iterator();
// while (sprite_iter.next()) |sprite_id| {
// const sprite = self.sprites.getAssumeExists(sprite_id);
// ImGUI.text("{f} - {?}", .{sprite_id, sprite.position});
// }
// }
// }
}
// TODO: This will always have a 1-frame delay.
@ -423,7 +396,11 @@ pub fn setClearColor(color: Color) void {
self.clear_color = color;
}
pub fn flush() void {
const FlushOptions = struct {
rebuild_spritesheets: bool = true
};
pub fn flush(opts: FlushOptions) void {
const self = &g_state;
if (self.quads.items.len == 0) {
@ -431,6 +408,7 @@ pub fn flush() void {
}
defer self.quads.clearRetainingCapacity();
if (opts.rebuild_spritesheets) {
var spritesheet_iter = self.spritesheets.iterator();
while (spritesheet_iter.next()) |spritesheet_id| {
const spritesheet = self.spritesheets.getAssumeExists(spritesheet_id);
@ -439,10 +417,6 @@ pub fn flush() void {
rebuildSpritesheetTextureIfNeeded(spritesheet_id);
}
}
if (sg.queryViewState(getBoundView().*) != .VALID) {
log.warn("Attempt to use view which isn't valid", .{});
return;
}
const vertex_buffer = self.bindings.vertex_buffers[0];
@ -468,7 +442,7 @@ pub fn flush() void {
var fs_params: shd.FsParams = .{
.texture_mode = 0,
};
const image = sg.queryViewImage(getBoundView().*);
const image = sg.queryViewImage(self.bindings.views[shd.VIEW_tex]);
if (sg.queryImagePixelformat(image) == .R8) {
fs_params.texture_mode = 1;
}
@ -477,17 +451,17 @@ pub fn flush() void {
sg.applyBindings(self.bindings);
sg.applyUniforms(shd.UB_vs_params, sg.asRange(&vs_params));
sg.applyUniforms(shd.UB_fs_params, sg.asRange(&fs_params));
assert(self.quads.items.len > 0);
sg.draw(0, @intCast(self.quads.items.len * 6), 1);
}
pub fn endFrame() void {
const self = &g_state;
flush();
flush(.{});
sg.endPass();
sg.commit();
self.frame_index += 1;
var spritesheet_iter = self.spritesheets.iterator();
while (spritesheet_iter.next()) |spritesheet_id| {
@ -499,8 +473,6 @@ pub fn endFrame() void {
} else if (self.transforms.items.len == 0) {
log.warn("Too many calls to transformPop()", .{});
}
self.frame_index += 1;
}
pub fn drawRectangle(pos: Vec2, size: Vec2, color: Color) void {
@ -605,28 +577,33 @@ pub fn initTexture(opts: TextureOptions) Texture.Id {
return id;
}
fn getBoundView() *sg.View {
fn isViewBound(view: sg.View) bool {
const self = &g_state;
return &self.bindings.views[shd.VIEW_tex];
const bound_view = &self.bindings.views[shd.VIEW_tex];
return bound_view.id == view.id;
}
fn isViewBound(view: sg.View) bool {
return getBoundView().id == view.id;
fn deinitTextureResources(texture: *Texture) void {
const self = &g_state;
if (isViewBound(texture.view)) {
const default_sprite = self.sprites.getAssumeExists(self.default_sprite);
const default_spritesheet = self.spritesheets.getAssumeExists(default_sprite.spritesheet);
const default_texture = self.textures.getAssumeExists(default_spritesheet.texture);
bindView(default_texture.view, .{ .rebuild_spritesheets = false });
}
sg.destroyImage(texture.image);
}
pub fn deinitTexture(id: Texture.Id) void {
const self = &g_state;
if (id == .nil) {
if (id == self.nil_texture) {
return;
}
if (self.textures.get(id)) |texture| {
const bound_view = getBoundView();
if (bound_view.id == texture.view.id) {
bound_view.id = sg.invalid_id;
}
sg.destroyImage(texture.image);
deinitTextureResources(texture);
sg.destroyView(texture.view);
self.textures.removeAssumeExists(id);
}
@ -672,6 +649,7 @@ pub fn setTexture(id: Texture.Id, texture_data: ImageData) void {
var texture_updated: bool = false;
if (sg.queryImageState(texture.image) == .VALID) {
// sg.queryImageInfo
const image_desc = sg.queryImageDesc(texture.image);
if (image_desc.width == new_image_desc.width and
image_desc.height == new_image_desc.height and
@ -681,19 +659,19 @@ pub fn setTexture(id: Texture.Id, texture_data: ImageData) void {
image_desc.usage.immutable == new_image_desc.usage.immutable and
image_desc.usage.dynamic_update
) {
log.debug("[{}] Update texture '{f}'", .{self.frame_index, id});
log.debug("Update texture '{f}'", .{id});
if (texture.updated_at == null or texture.updated_at.? != self.frame_index) {
sg.updateImage(texture.image, image_data);
texture_updated = true;
texture.updated_at = self.frame_index;
} else {
log.warn("Attempt to update the same texture multiple times per frame, texture: {f}", .{id});
log.warn("Attempt to update the same texture multiple times per frame", .{});
}
}
}
if (!texture_updated) {
log.debug("[{}] Create image-view, texture={f}", .{self.frame_index, id});
log.debug("Create image-view, texture={f}", .{id});
const new_image = sg.makeImage(new_image_desc);
if (sg.queryImageState(new_image) != .VALID) {
log.warn("makeImage() failed", .{});
@ -711,13 +689,11 @@ pub fn setTexture(id: Texture.Id, texture_data: ImageData) void {
return;
}
sg.destroyImage(texture.image);
deinitTextureResources(texture);
texture.image = new_image;
texture.updated_at = null;
log.debug("is dynamic {f}, {}", .{id, texture.dynamic});
if (texture.dynamic) {
log.debug("update texture {f}", .{id});
sg.updateImage(new_image, image_data);
texture.updated_at = self.frame_index;
}
@ -736,11 +712,20 @@ pub fn drawTexture(id: Texture.Id, pos: Vec2, size: Vec2, color: Color) void {
});
}
fn bindView(view: sg.View) void {
_ = view; // autofix
fn bindView(view: sg.View, opts: FlushOptions) void {
const self = &g_state;
_ = self; // autofix
const view_state = sg.queryViewState(view);
if (view_state != .VALID and view_state != .ALLOC) {
log.warn("Attempt to bind non-valid view: state={}", .{view_state});
return;
}
const bound_view = &self.bindings.views[shd.VIEW_tex];
if (bound_view.id != view.id) {
flush(opts);
bound_view.* = view;
}
}
pub fn setDefaultSampler(sampler: Sampler) void {
@ -788,17 +773,7 @@ pub fn draw(opts: DrawOptions) void {
return;
}
const view_state = sg.queryViewState(view);
if (view_state == .VALID or view_state == .ALLOC) {
const bound_view = getBoundView();
if (bound_view.id != view.id) {
flush();
bound_view.* = view;
}
} else {
log.warn("Attempt to bind non-valid view: state={}", .{view_state});
return;
}
bindView(view, .{});
const sampler = switch (opts.sampler orelse self.default_sampler) {
.linear => self.linear_sampler,
@ -806,12 +781,12 @@ pub fn draw(opts: DrawOptions) void {
};
const bound_sampler = &self.bindings.samplers[shd.SMP_smp];
if (bound_sampler.id != sampler.id) {
flush();
flush(.{});
bound_sampler.* = sampler;
}
if (self.quads.items.len == self.quads.capacity) {
flush();
flush(.{});
}
if (getTransformPtr()) |transform| {
@ -868,7 +843,6 @@ const SetSpriteOptions = struct {
pub fn setSprite(id: Sprite.Id, opts: SetSpriteOptions) void {
const self = &g_state;
const sprite = self.sprites.get(id) orelse {
log.warn("Attempt to set sprite that doesn't exist: {}", .{id});
return;
@ -923,14 +897,12 @@ pub fn setSprite(id: Sprite.Id, opts: SetSpriteOptions) void {
const new_size = Vec2.initFromInt(u32, sprite_data.width, sprite_data.height);
log.debug("set sprite on {f}", .{sprite.spritesheet});
if (old_size == null or !old_size.?.eql(new_size) or sprite.position == null) {
if (old_size != null and old_size.?.eql(new_size) and sprite.position != null) {
spritesheet.needs_texture_rebuild = true;
} else {
sprite.position = null;
spritesheet.needs_repack = true;
}
spritesheet.needs_texture_rebuild = true;
}
// WARNING: This will change the UV coordinates of all sprites.
@ -943,7 +915,7 @@ fn repackSpritesheet(id: Spritesheet.Id) void {
return;
};
log.debug("[{}] Repack spritesheet: {f}", .{self.frame_index, id});
log.debug("Repack spritesheet: {f}", .{id});
// TODO: Add a smarter startegy for picking the initial texture size.
// One idea is to calculate the sum area of all sprites and pick a atlas size based on that.
@ -1022,7 +994,7 @@ fn rebuildSpritesheetTextureIfNeeded(id: Spritesheet.Id) void {
return;
}
log.debug("[{}] Rebuild spritesheet texture: {f}", .{self.frame_index, id});
log.debug("Rebuild spritesheet texture: {f}", .{id});
const image_data = ImageData.init(
self.gpa,
@ -1293,12 +1265,12 @@ pub fn getGlyph(id: Font.Id, index: GlyphIndex, scale_x: f32, scale_y: f32) ?*Fo
};
glyph = font.cache.get(glyph_id);
glyph.box = stb_font.getGlyphBitmapBox(glyph_key.index, glyph_key.scale_x, glyph_key.scale_y);
glyph.sprite = null;
const box_width: u32 = @intCast(glyph.box.x1 - glyph.box.x0);
const box_height: u32 = @intCast(glyph.box.y1 - glyph.box.y0);
if (box_width > 0 and box_height > 0) {
const sprite = initSprite(.{ .spritesheet = font.spritesheet, .padding = 1 });
assert(glyph.sprite == Sprite.Id.nil);
glyph.sprite = initSprite(.{ .spritesheet = font.spritesheet, .padding = 1 });
assert(box_width < Font.Glyph.max_width);
assert(box_height < Font.Glyph.max_height);
@ -1316,10 +1288,9 @@ pub fn getGlyph(id: Font.Id, index: GlyphIndex, scale_x: f32, scale_y: f32) ?*Fo
glyph_key.scale_x, glyph_key.scale_y,
glyph_key.index
);
setSprite(sprite, .{ .image = bitmap });
assert(glyph.sprite == null);
glyph.sprite = sprite;
setSprite(glyph.sprite, .{ .image = bitmap });
} else {
glyph.sprite = .nil;
}
}
glyph.used_this_frame = true;
@ -1337,7 +1308,7 @@ pub const TextRunLayout = struct {
const GlyphRect = struct {
rect: Rect,
sprite: ?Sprite.Id,
sprite: Sprite.Id,
};
pub fn init(font: Font.Id, height: f32) TextRunLayout {
@ -1435,10 +1406,9 @@ pub fn drawText(id: Font.Id, opts: DrawTextOptions) void {
while (iter.nextCodepoint()) |codepoint| {
const glyph_index = getGlyphIndex(id, codepoint) orelse continue;
const glyph_layout = layout.next(glyph_index) orelse continue;
const glyph_sprite = glyph_layout.sprite orelse continue;
drawSprite(
glyph_sprite,
glyph_layout.sprite,
glyph_layout.rect.pos.add(pos),
glyph_layout.rect.size,
opts.color
@ -2163,7 +2133,7 @@ pub const Font = struct {
key: Key,
box: STBTrueType.Box,
sprite: ?Sprite.Id,
sprite: Sprite.Id,
used_this_frame: bool,
const max_width: u32 = 512;
@ -2199,9 +2169,7 @@ pub const Font = struct {
}
fn deinit(self: Glyph) void {
if (self.sprite) |sprite| {
deinitSprite(sprite);
}
deinitSprite(self.sprite);
}
};
};

View File

@ -503,92 +503,3 @@ pub fn collapsingHeader(label: []const u8) bool {
ig.ImGuiTreeNodeFlags_None
);
}
pub fn beginTable(id: [*c]const u8, columns: u32, flags: ig.ImGuiTableFlags) bool {
if (isDisabled()) {
return false;
}
return ig.igBeginTable(id, @intCast(columns), flags);
}
pub fn endTable() void {
if (isDisabled()) {
return;
}
ig.igEndTable();
}
pub fn tableNextColumn() void {
if (isDisabled()) {
return;
}
_ = ig.igTableNextColumn();
}
pub fn tableNextRow() void {
if (isDisabled()) {
return;
}
_ = ig.igTableNextRow();
}
pub fn tableSetColumnIndex(index: usize) void {
if (isDisabled()) {
return;
}
_ = ig.igTableSetColumnIndex(@intCast(index));
}
pub fn tableSetupColumn(label: [*c]const u8, flags: ig.ImGuiTableColumnFlags) void {
if (isDisabled()) {
return;
}
ig.igTableSetupColumn(label, flags);
}
pub fn tableHeadersRow() void {
if (isDisabled()) {
return;
}
ig.igTableHeadersRow();
}
const PlotLinesOptions = struct {
label: [*c]const u8,
values: []f32,
ex: ?struct {
graph_width: f32 = 0,
graph_height: f32 = 0,
scale_min: f32 = 0,
scale_max: f32 = 1,
stride: u32 = 4,
} = null
};
pub fn plotLines(opts: PlotLinesOptions) void {
if (isDisabled()) {
return;
}
if (opts.ex) |ex| {
ig.igPlotLinesEx(
opts.label,
opts.values.ptr, @intCast(opts.values.len),
0,
null,
ex.scale_min,
ex.scale_max,
.{ .x = ex.graph_width, .y = ex.graph_height },
@intCast(ex.stride)
);
} else {
ig.igPlotLines(opts.label, opts.values.ptr, @intCast(opts.values.len));
}
}

View File

@ -6,16 +6,9 @@ const sokol = @import("sokol");
const Math = @import("math");
const Vec2 = Math.Vec2;
const Nanoseconds = @import("./root.zig").Nanoseconds;
const Input = @This();
// TODO: Make this configurable from the app
const key_repeat_first: Nanoseconds = 0.4 * std.time.ns_per_s;
const key_repeat_delay: Nanoseconds = 0.2 * std.time.ns_per_s;
now: Nanoseconds,
delta_time: Nanoseconds,
key_code_mapping: std.EnumMap(KeyCode, u21),
window_size: Vec2,
focused: bool,
@ -25,13 +18,8 @@ mouse_position: ?Vec2,
mouse_delta: Vec2,
mouse_scroll: Vec2,
key_code_mapping: std.EnumMap(KeyCode, u21),
last_key_repeat_at: std.EnumMap(KeyCode, Nanoseconds),
pub fn init(window_size: Vec2) Input {
return Input{
.now = 0,
.delta_time = 0,
.key_code_mapping = .{},
.focused = false,
.keyboard = .empty,
@ -39,8 +27,7 @@ pub fn init(window_size: Vec2) Input {
.mouse_position = null,
.mouse_delta = .init(0, 0),
.mouse_scroll = .init(0, 0),
.window_size = window_size,
.last_key_repeat_at = .{}
.window_size = window_size
};
}
@ -53,33 +40,7 @@ pub fn isKeyReleased(self: Input, key: KeyCode) bool {
}
pub fn isKeyDown(self: Input, key: KeyCode) bool {
return self.keyboard.pressed_at.contains(key);
}
pub fn getKeyDown(self: Input, key: KeyCode) ?Nanoseconds {
return self.keyboard.getDown(key, self.now);
}
pub fn isKeyRepeat(self: *Input, key: KeyCode) bool {
const pressed_at = self.keyboard.pressed_at.get(key) orelse return false;
var next_repeat_at: Nanoseconds = undefined;
if (self.last_key_repeat_at.get(key)) |last_repeat_at| {
next_repeat_at = last_repeat_at + key_repeat_delay;
} else {
next_repeat_at = pressed_at + key_repeat_first;
}
if (self.now >= next_repeat_at) {
self.last_key_repeat_at.put(key, next_repeat_at);
return true;
} else {
return false;
}
}
pub fn isKeyPressedOrRepeat(self: *Input, key: KeyCode) bool {
return self.isKeyPressed(key) or self.isKeyRepeat(key);
return self.keyboard.down.contains(key);
}
pub fn isMousePressed(self: Input, button: MouseButton) bool {
@ -91,11 +52,7 @@ pub fn isMouseReleased(self: Input, button: MouseButton) bool {
}
pub fn isMouseDown(self: Input, button: MouseButton) bool {
return self.mouse_buttons.pressed_at.contains(button);
}
pub fn getMouseDown(self: Input, button: MouseButton) ?Nanoseconds {
return self.mouse_buttons.getDown(button, self.now);
return self.mouse_buttons.down.contains(button);
}
pub const KeyCode = enum(std.math.IntFittingRange(0, sokol.app.max_keycodes-1)) {
@ -255,35 +212,28 @@ fn KeyStateType(T: type) type {
return struct {
pressed: std.EnumSet(T),
released: std.EnumSet(T),
pressed_at: std.EnumMap(T, Nanoseconds),
down: std.EnumSet(T),
pub const empty = @This(){
.pressed = .empty,
.released = .empty,
.pressed_at = .{},
.down = .empty,
};
pub fn press(self: *@This(), key: T, now: Nanoseconds) void {
pub fn press(self: *@This(), key: T) void {
self.pressed.insert(key);
self.pressed_at.put(key, now);
self.down.insert(key);
}
pub fn release(self: *@This(), key: T) void {
self.released.insert(key);
self.pressed_at.remove(key);
}
pub fn getDown(self: @This(), key: T, now: Nanoseconds) ?Nanoseconds {
if (self.pressed_at.get(key)) |pressed_at| {
return now - pressed_at;
}
return null;
self.down.remove(key);
}
pub fn releaseAll(self: *@This()) void {
var iter = self.pressed_at.iterator();
while (iter.next()) |e| {
self.release(e.key);
var iter = self.down.iterator();
while (iter.next()) |key| {
self.release(key);
}
}
};

View File

@ -27,7 +27,6 @@ pub const ImGUI = @import("./imgui.zig");
pub const Gfx = @import("./graphics.zig");
pub const Input = @import("./input.zig");
pub const Audio = @import("./audio.zig");
pub const SlotMapType = @import("./slot_map.zig").SlotMapType;
const EmbeddedAssets = @import("embedded_assets");
@ -106,11 +105,10 @@ fn PlatformType(App: type) type {
_ = self.frame_arena.reset(.free_all); // TODO: make arena reset mode configurable
const now = Io.Timestamp.now(self.io, .awake);
const t = self.started_at.durationTo(now);
const dt = self.last_frame_at.durationTo(now);
self.last_frame_at = now;
self.input.now = @intCast(self.started_at.durationTo(now).nanoseconds);
self.input.delta_time = @intCast(self.last_frame_at.durationTo(now).nanoseconds);
if (self.input.keyboard.pressed.contains(.F4)) {
self.show_imgui = !self.show_imgui;
}
@ -128,6 +126,8 @@ fn PlatformType(App: type) type {
if (@hasDecl(App, "frame")) {
const plt = Frame{
.t = t.nanoseconds,
.dt = dt.nanoseconds,
.gpa = self.gpa,
.arena = self.arena.allocator(),
.io = self.io,
@ -139,26 +139,8 @@ fn PlatformType(App: type) type {
try self.app.frame(plt);
}
Gfx.flush();
if (ImGUI.beginWindow(.{
.name = "Platform",
.size = .init(300, 400)
})) {
defer ImGUI.endWindow();
_ = ImGUI.beginTabBar("platform tab bar");
defer ImGUI.endTabBar();
if (ImGUI.beginTabItem("Graphics")) {
defer ImGUI.endTabItem();
Gfx.flush(.{});
Gfx.showDebug();
}
if (ImGUI.beginTabItem("Audio")) {
defer ImGUI.endTabItem();
Audio.showDebug();
}
}
ImGUI.endFrame();
Gfx.endFrame();
@ -195,9 +177,7 @@ fn PlatformType(App: type) type {
return false;
}
const now = self.started_at.durationTo(Io.Timestamp.now(self.io, .awake));
input.keyboard.press(key, @intCast(now.nanoseconds));
input.keyboard.press(key);
self.last_key_pressed = key;
},
.key_released => |key| {
@ -206,16 +186,13 @@ fn PlatformType(App: type) type {
}
input.keyboard.release(key);
input.last_key_repeat_at.remove(key);
},
.mouse_pressed => |button| {
if (input.mouse_position == null or input.isMouseDown(button)) {
return false;
}
const now = self.started_at.durationTo(Io.Timestamp.now(self.io, .awake));
input.mouse_buttons.press(button, @intCast(now.nanoseconds));
input.mouse_buttons.press(button);
},
.mouse_released => |button| {
if (input.mouse_position == null or !input.isMouseDown(button)) {
@ -279,8 +256,8 @@ fn PlatformType(App: type) type {
}
assert(input.mouse_position == null);
assert(input.keyboard.pressed_at.count() == 0);
assert(input.mouse_buttons.pressed_at.count() == 0);
assert(input.keyboard.down.eql(.empty));
assert(input.mouse_buttons.down.eql(.empty));
input.focused = false;
}
}
@ -311,13 +288,13 @@ fn PlatformType(App: type) type {
}
if (e == .unfocused) {
var key_iter = input.keyboard.pressed_at.iterator();
while (key_iter.next()) |key_pressed_at| {
self.appendEvent(.{ .key_released = key_pressed_at.key });
var key_iter = input.keyboard.down.iterator();
while (key_iter.next()) |key| {
self.appendEvent(.{ .key_released = key });
}
var mouse_buttons_iter = input.mouse_buttons.pressed_at.iterator();
while (mouse_buttons_iter.next()) |key_pressed_at| {
self.appendEvent(.{ .mouse_released = key_pressed_at.key });
var mouse_buttons_iter = input.mouse_buttons.down.iterator();
while (mouse_buttons_iter.next()) |button| {
self.appendEvent(.{ .mouse_released = button });
}
self.appendEvent(.{ .mouse_leave = {} });
}
@ -571,9 +548,12 @@ pub const Deinit = struct {
io: Io,
};
pub const Nanoseconds = i64;
pub const Nanoseconds = i96;
pub const Frame = struct {
t: Nanoseconds,
dt: Nanoseconds,
gpa: Allocator,
arena: Allocator,
frame: Allocator,
@ -582,16 +562,16 @@ pub const Frame = struct {
input: *Input,
input_events: []Input.Event,
fn nanosecondsToSeconds(nanoseconds: Nanoseconds) f32 {
fn nanosecondsToSeconds(nanoseconds: i96) f32 {
return @floatCast(@as(f64, @floatFromInt(nanoseconds)) / std.time.ns_per_s);
}
pub fn deltaTime(self: Frame) f32 {
return nanosecondsToSeconds(self.input.delta_time);
return nanosecondsToSeconds(self.dt);
}
pub fn time(self: Frame) f32 {
return nanosecondsToSeconds(self.input.now);
return nanosecondsToSeconds(self.t);
}
};
@ -626,7 +606,7 @@ pub fn run(App: type, opts: RunOptions) void {
.last_key_press_is_repeat = false,
.last_key_pressed = null,
.frame_arena = .init(gpa),
.show_imgui = false,
.show_imgui = builtin.mode == .Debug,
.assets = .init(gpa, io, assets_dir),
.last_mouse_position = null
};

View File

@ -87,7 +87,7 @@ pub fn SlotMapType(Index: type, Generation: type, Value: type) type {
};
pub fn clearRetainingCapacity(self: *Self) void {
self.* = .initBuffer(self.slots.items);
self.* = .init(self.slots.items);
}
fn insertHole(self: *Self, index: Index) void {
@ -129,11 +129,7 @@ pub fn SlotMapType(Index: type, Generation: type, Value: type) type {
pub fn unusedCapacity(self: *Self) usize {
const capacity = @min(self.slots.capacity, std.math.maxInt(Index));
return capacity - self.count();
}
pub fn count(self: *Self) usize {
return self.slots.items.len - self.hole_count;
return capacity - self.slots.items.len + self.hole_count;
}
pub fn insertAssumeCapacity(self: *Self) Id {
@ -219,21 +215,11 @@ pub fn SlotMapType(Index: type, Generation: type, Value: type) type {
};
}
pub fn initBuffer(slots: []Slot) Self {
pub fn init(slots: []Slot) Self {
var self: Self = .empty;
self.slots = .initBuffer(slots);
return self;
}
pub fn initCapacity(gpa: Allocator, capacity: usize) !Self {
var self: Self = .empty;
self.slots = try .initCapacity(gpa, capacity);
return self;
}
pub fn deinit(self: *Self, gpa: Allocator) void {
self.slots.deinit(gpa);
}
};
}