Level loading functionnal.

This commit is contained in:
KikooDX 2021-02-24 12:20:38 +01:00
parent 6d732d65b1
commit 572c94f78f
4 changed files with 54 additions and 9 deletions

11
gen_sample.lua Executable file
View File

@ -0,0 +1,11 @@
#!/usr/bin/lua
local out = io.open("sample.kble", "wb")
out:write(string.char(
2,
0, 2,
0, 2,
0, 1,
0, 0,
0, 0,
1, 1))
out:close()

Binary file not shown.

View File

@ -52,12 +52,7 @@ pub fn init(allocator: *std.mem.Allocator, width: u16, height: u16) !Self {
/// Load level content from given absolute path. Expect the KBLE file format (see
/// `kbleformat.md` for more details.
pub fn init_load(allocator: *std.mem.Allocator, kble_file_path: []const u8) !Self {
var self = Self{
.width = undefined,
.height = undefined,
.content = undefined,
.selection = undefined,
};
var self: Self = undefined;
const expected_bytes_per_cell = @sizeOf(cell_type);
@ -74,10 +69,48 @@ pub fn init_load(allocator: *std.mem.Allocator, kble_file_path: []const u8) !Sel
// Read first byte and check than the value matches the size of cell_type.
{
const cell_spec_byte = try(reader.readByte());
const cell_spec_byte = try reader.readByte();
assert(cell_spec_byte == expected_bytes_per_cell);
}
// Read four bytes and use them for width and height. Two bytes each.
{
const width_byte1: u8 = try reader.readByte();
const width_byte2: u8 = try reader.readByte();
const height_byte1: u8 = try reader.readByte();
const height_byte2: u8 = try reader.readByte();
const width: u16 = @intCast(u16, width_byte1) * 256 + @intCast(u16, width_byte2);
const height: u16 = @intCast(u16, height_byte1) * 256 + @intCast(u16, height_byte2);
std.log.info("Cell size: {}\nWidth/height: {}·{} ; {}·{} => {} ; {}", .{
expected_bytes_per_cell,
width_byte1,
width_byte2,
height_byte1,
height_byte2,
width,
height,
});
// Non-null width and height.
assert(width > 0);
assert(height > 0);
self = try Self.init(allocator, width, height);
}
// Read the rest of the file and assign to .content accordingly.
{
var i: u32 = 0;
while (i < self.width * self.height) : (i += 1) {
const byte1 = try reader.readByte();
const byte2 = try reader.readByte();
const cell = @intCast(u16, byte1) * 256 + @intCast(u16, byte2);
self.content[i] = cell;
}
}
return self;
}
@ -234,5 +267,5 @@ test "load level from existing file" {
const allocator = &arena.allocator;
var level: Self = try Self.init_load(allocator, "sample.kble");
//defer level.deinit(allocator);
defer level.deinit(allocator);
}

View File

@ -41,7 +41,8 @@ pub fn main() void {
ray.SetTargetFPS(60);
// Create level.
var level: Level = Level.init(allocator, 16, 16) catch unreachable;
//var level: Level = Level.init(allocator, 16, 16) catch unreachable;
var level: Level = Level.init_load(allocator, "sample.kble") catch unreachable;
defer level.deinit(allocator);
// Create camera.