Preallocate texture VRAM, move files around
This commit is contained in:
@@ -9,8 +9,8 @@ const voxels = @import("../voxels.zig");
|
||||
|
||||
const Atom = @import("../engine/Atom.zig").Atom;
|
||||
const Engine = @import("../engine/Engine.zig");
|
||||
const Materials = @import("Materials.zig");
|
||||
const Textures = @import("Textures.zig");
|
||||
const Materials = @import("../engine/Materials.zig");
|
||||
const Textures = @import("../engine/Textures.zig");
|
||||
|
||||
pub const Id = enum(u16) {
|
||||
// VOLATILE Synchronize explicit values with `init` implementation.
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
const Chunk = @This();
|
||||
const std = @import("std");
|
||||
|
||||
const ctx = @import("../AppContext.zig");
|
||||
const math = @import("../math.zig");
|
||||
const shaders = @import("../shaders.zig");
|
||||
const vk = @import("vulkan");
|
||||
const vm = @import("vecmath");
|
||||
const voxels = @import("../voxels.zig");
|
||||
|
||||
const Blocks = @import("Blocks.zig");
|
||||
const CommandBuffer = @import("../engine/CommandBuffer.zig");
|
||||
const Engine = @import("../engine/Engine.zig");
|
||||
const Game = @import("../Game.zig");
|
||||
const GenericBuffer = @import("../engine/GenericBuffer.zig").GenericBuffer;
|
||||
const Materials = @import("Materials.zig");
|
||||
|
||||
const ObjectUniformsBuffer = GenericBuffer(void, shaders.ObjectUniforms);
|
||||
|
||||
pub const chunk_size = 16;
|
||||
|
||||
const initial_capacity = 256;
|
||||
var next_chunk_id: std.atomic.Value(u64) = .init(0);
|
||||
|
||||
/// To get the block at coordinates (x, y, z) relative to the chunk, read the
|
||||
/// value at `blocks[z][y][x]`.
|
||||
blocks: [chunk_size][chunk_size][chunk_size]Blocks.Id,
|
||||
origin: vm.Vector3,
|
||||
descriptor_set: vk.DescriptorSet,
|
||||
object_buffer: ObjectUniformsBuffer,
|
||||
object_count: u32,
|
||||
|
||||
/// For debug purposes, a unique "name" per chunk instance.
|
||||
chunk_id: u64,
|
||||
|
||||
pub const InitInfo = struct {
|
||||
origin: vm.Vector3,
|
||||
descriptor_pool: vk.DescriptorPool,
|
||||
per_batch_descriptor_set_layout: vk.DescriptorSetLayout,
|
||||
};
|
||||
|
||||
pub const Neighbors = std.enums.EnumFieldStruct(voxels.Orientation, ?*const Chunk, null);
|
||||
|
||||
pub fn init(init_info: InitInfo) !Chunk {
|
||||
const engine = ctx.engine;
|
||||
|
||||
const descriptor_set = try engine.allocateDescriptorSet(.{
|
||||
.descriptor_pool = init_info.descriptor_pool,
|
||||
.set_layout = init_info.per_batch_descriptor_set_layout,
|
||||
});
|
||||
errdefer engine.freeDescriptorSet(init_info.descriptor_pool, descriptor_set);
|
||||
|
||||
var object_buffer: ObjectUniformsBuffer = try .init(.{
|
||||
.usage = .storage,
|
||||
.target_queue = .graphics,
|
||||
.array_capacity = initial_capacity,
|
||||
});
|
||||
errdefer object_buffer.deinit();
|
||||
|
||||
try engine.updateDescriptorSets(.{
|
||||
.writes = &.{
|
||||
.{
|
||||
.dst_set = descriptor_set,
|
||||
.dst_binding = 0,
|
||||
.dst_array_element = 0,
|
||||
.descriptor_type = .storage_buffer,
|
||||
.descriptor_infos = .{
|
||||
.buffer = &.{
|
||||
.{
|
||||
.buffer = object_buffer.buffer,
|
||||
.offset = 0,
|
||||
.range = vk.WHOLE_SIZE,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const chunk_id = next_chunk_id.fetchAdd(1, .monotonic);
|
||||
engine.setObjectName(descriptor_set, "DS Chunk[{d}]", .{chunk_id});
|
||||
engine.setObjectName(object_buffer.buffer, "B Chunk[{d}]", .{chunk_id});
|
||||
engine.setObjectName(object_buffer.device_memory, "DM Chunk[{d}]", .{chunk_id});
|
||||
|
||||
return .{
|
||||
.blocks = .{.{[_]Blocks.Id{.air} ** chunk_size} ** chunk_size} ** chunk_size,
|
||||
.origin = init_info.origin,
|
||||
.descriptor_set = descriptor_set,
|
||||
.object_buffer = object_buffer,
|
||||
.object_count = 0,
|
||||
.chunk_id = chunk_id,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Chunk, descriptor_pool: vk.DescriptorPool) void {
|
||||
const engine = ctx.engine;
|
||||
|
||||
std.log.scoped(.deinit).debug("Deinitializing chunk {d} with {s}#{X}", .{ self.chunk_id, @typeName(vk.DescriptorPool), @intFromEnum(descriptor_pool) });
|
||||
|
||||
self.object_buffer.deinit();
|
||||
engine.freeDescriptorSet(descriptor_pool, self.descriptor_set);
|
||||
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
pub fn refresh(self: *Chunk, blocks: *const Blocks, neighbors: Neighbors) !void {
|
||||
const allocator_frame = ctx.allocator_frame;
|
||||
const engine = ctx.engine;
|
||||
|
||||
var uniforms: std.ArrayList(shaders.ObjectUniforms) = try .initCapacity(allocator_frame, initial_capacity);
|
||||
|
||||
for (self.blocks, 0..) |plane, iz| {
|
||||
const fz: f32 = @floatFromInt(iz);
|
||||
for (plane, 0..) |row, iy| {
|
||||
const fy: f32 = @floatFromInt(iy);
|
||||
for (row, 0..) |id, ix| {
|
||||
const fx: f32 = @floatFromInt(ix);
|
||||
const block: *const Blocks.Definition = &blocks.array.items[id.toInt()];
|
||||
const origin = vm.Vector3.add(self.origin, .init(fx, fy, fz));
|
||||
|
||||
inline for (@typeInfo(voxels.Orientation).@"enum".fields) |field| {
|
||||
const side = @field(voxels.Orientation, field.name);
|
||||
const material = @field(block.walls, field.name).material;
|
||||
if (material != .empty and self.getOpposite(side, ix, iy, iz, blocks, neighbors) == .empty) {
|
||||
const matrix = getMatrix(side, origin);
|
||||
try uniforms.append(allocator_frame, .{
|
||||
.matrixOStoWS = matrix,
|
||||
.matrixOStoWSNormal = matrix,
|
||||
.material = material,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const object_count: u32 = @intCast(uniforms.items.len);
|
||||
if (self.object_buffer.array_capacity < object_count) {
|
||||
const desired_capacity = std.math.ceilPowerOfTwoAssert(u32, object_count);
|
||||
const new_object_buffer: ObjectUniformsBuffer = try .init(.{
|
||||
.usage = .storage,
|
||||
.target_queue = .graphics,
|
||||
.array_capacity = desired_capacity,
|
||||
});
|
||||
|
||||
try engine.updateDescriptorSets(.{
|
||||
.writes = &.{
|
||||
.{
|
||||
.dst_set = self.descriptor_set,
|
||||
.dst_binding = 0,
|
||||
.dst_array_element = 0,
|
||||
.descriptor_type = .storage_buffer,
|
||||
.descriptor_infos = .{
|
||||
.buffer = &.{
|
||||
.{
|
||||
.buffer = new_object_buffer.buffer,
|
||||
.offset = 0,
|
||||
.range = vk.WHOLE_SIZE,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
self.object_buffer.deinit();
|
||||
self.object_buffer = new_object_buffer;
|
||||
engine.setObjectName(new_object_buffer.buffer, "B Chunk[{d}]", .{self.chunk_id});
|
||||
engine.setObjectName(new_object_buffer.device_memory, "DM Chunk[{d}]", .{self.chunk_id});
|
||||
}
|
||||
|
||||
try self.object_buffer.write(.{ .elements = uniforms.items });
|
||||
self.object_count = object_count;
|
||||
}
|
||||
|
||||
pub fn draw(self: *const Chunk, layout: vk.PipelineLayout, command_buffer: CommandBuffer) void {
|
||||
command_buffer.bindDescriptorSets(.graphics, layout, 1, &.{self.descriptor_set}, &.{});
|
||||
command_buffer.drawIndexed(.{ .index_count = 6, .instance_count = self.object_count });
|
||||
}
|
||||
|
||||
fn getOpposite(self: *const Chunk, comptime side: voxels.Orientation, x: usize, y: usize, z: usize, blocks: *const Blocks, neighbors: Neighbors) Materials.Id {
|
||||
return switch (side) {
|
||||
.positive_x => if (x + 1 < chunk_size)
|
||||
blocks.array.items[self.blocks[z][y][x + 1].toInt()].walls.negative_x.material
|
||||
else if (neighbors.positive_x) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[z][y][0].toInt()].walls.negative_x.material
|
||||
else
|
||||
.empty,
|
||||
.negative_x => if (x > 0)
|
||||
blocks.array.items[self.blocks[z][y][x - 1].toInt()].walls.positive_x.material
|
||||
else if (neighbors.negative_x) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[z][y][chunk_size - 1].toInt()].walls.positive_x.material
|
||||
else
|
||||
.empty,
|
||||
.positive_y => if (y + 1 < chunk_size)
|
||||
blocks.array.items[self.blocks[z][y + 1][x].toInt()].walls.negative_y.material
|
||||
else if (neighbors.positive_y) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[z][0][x].toInt()].walls.negative_y.material
|
||||
else
|
||||
.empty,
|
||||
.negative_y => if (y > 0)
|
||||
blocks.array.items[self.blocks[z][y - 1][x].toInt()].walls.positive_y.material
|
||||
else if (neighbors.negative_y) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[z][chunk_size - 1][x].toInt()].walls.positive_y.material
|
||||
else
|
||||
.empty,
|
||||
.positive_z => if (z + 1 < chunk_size)
|
||||
blocks.array.items[self.blocks[z + 1][y][x].toInt()].walls.negative_z.material
|
||||
else if (neighbors.positive_z) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[0][y][x].toInt()].walls.negative_z.material
|
||||
else
|
||||
.empty,
|
||||
.negative_z => if (z > 0)
|
||||
blocks.array.items[self.blocks[z - 1][y][x].toInt()].walls.positive_z.material
|
||||
else if (neighbors.negative_z) |neighbor|
|
||||
blocks.array.items[neighbor.blocks[chunk_size - 1][y][x].toInt()].walls.positive_z.material
|
||||
else
|
||||
.empty,
|
||||
};
|
||||
}
|
||||
|
||||
fn getMatrix(comptime side: voxels.Orientation, origin: vm.Vector3) vm.Matrix4x4 {
|
||||
return switch (side) {
|
||||
// zig fmt: off
|
||||
.positive_x => .init(
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
1, 0, 0, 0,
|
||||
origin.x + 1, origin.y, origin.z, 1,
|
||||
),
|
||||
.negative_x => .init(
|
||||
0, -1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
-1, 0, 0, 0,
|
||||
origin.x, origin.y + 1, origin.z, 1,
|
||||
),
|
||||
.positive_y => .init(
|
||||
-1, 0, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, 1, 0, 0,
|
||||
origin.x + 1, origin.y + 1, origin.z, 1,
|
||||
),
|
||||
.negative_y => .init(
|
||||
1, 0, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
0, -1, 0, 0,
|
||||
origin.x, origin.y, origin.z, 1,
|
||||
),
|
||||
.positive_z => .init(
|
||||
1, 0, 0, 0,
|
||||
0, 1, 0, 0,
|
||||
0, 0, 1, 0,
|
||||
origin.x, origin.y, origin.z + 1, 1,
|
||||
),
|
||||
.negative_z => .init(
|
||||
1, 0, 0, 0,
|
||||
0, -1, 0, 0,
|
||||
0, 0, -1, 0,
|
||||
origin.x, origin.y + 1, origin.z, 1,
|
||||
),
|
||||
// zig fmt: on
|
||||
};
|
||||
}
|
||||
@@ -1,333 +0,0 @@
|
||||
//! Module for loading persistent materials.
|
||||
|
||||
const Materials = @This();
|
||||
const std = @import("std");
|
||||
|
||||
const ctx = @import("../AppContext.zig");
|
||||
const media = @import("media");
|
||||
const shaders = @import("../shaders.zig");
|
||||
const vk = @import("vulkan");
|
||||
|
||||
const Atom = @import("../engine/Atom.zig").Atom;
|
||||
const Engine = @import("../engine/Engine.zig");
|
||||
const Textures = @import("Textures.zig");
|
||||
|
||||
pub const Id = enum(u16) {
|
||||
// VOLATILE Synchronize explicit values with `init` implementation.
|
||||
|
||||
/// A material ID that can be used as a "null" material. An object with this
|
||||
/// material ID must not be rendered. If this ID is rendered, an "error"
|
||||
/// replacement material will be used.
|
||||
empty,
|
||||
_,
|
||||
|
||||
/// Cast an integer into an ID. This can produce an invalid ID.
|
||||
pub fn fromInt(value: u16) Id {
|
||||
return @enumFromInt(value);
|
||||
}
|
||||
|
||||
/// Cast an index into an ID. This can produce an invalid ID. The caller
|
||||
/// asserts that the index is not greater than the max ID value.
|
||||
pub fn fromIndex(index: usize) Id {
|
||||
std.debug.assert(index < max_materials);
|
||||
return @enumFromInt(@as(u16, @intCast(index)));
|
||||
}
|
||||
|
||||
/// Cast an index into an ID. This can produce an invalid ID. Returns an
|
||||
/// error if the index is greater than the max ID value.
|
||||
pub fn fromIndexSafe(index: usize) error{Overflow}!Id {
|
||||
if (index >= max_materials) return error.Overflow;
|
||||
return @enumFromInt(@as(u16, @intCast(index)));
|
||||
}
|
||||
|
||||
/// Cast an ID into an integer.
|
||||
pub fn toInt(self: Id) u16 {
|
||||
return @intFromEnum(self);
|
||||
}
|
||||
};
|
||||
|
||||
pub const Key = struct {
|
||||
/// Atom representing the filename of the material.
|
||||
filename: Atom,
|
||||
};
|
||||
|
||||
/// Maps a key value to a material ID. Preallocated with `allocator_general`.
|
||||
map: std.AutoHashMapUnmanaged(Key, Id),
|
||||
/// Stores all material data in a single contiguous storage buffer. Use the
|
||||
/// material ID as an index into this buffer.
|
||||
material_buffer: shaders.MaterialBuffer,
|
||||
/// The amount of materials currently loaded.
|
||||
material_count: usize,
|
||||
|
||||
/// With `@sizeOf(Material) == 52` and `max_materials == 4096`, the material
|
||||
/// storage buffer should take 208 kiB in VRAM.
|
||||
pub const max_materials = 4096;
|
||||
|
||||
pub fn init() !Materials {
|
||||
const allocator_general = ctx.allocator_general;
|
||||
|
||||
var map: std.AutoHashMapUnmanaged(Key, Id) = .empty;
|
||||
errdefer map.deinit(allocator_general);
|
||||
try map.ensureTotalCapacity(allocator_general, max_materials);
|
||||
|
||||
var material_buffer = try shaders.MaterialBuffer.init(.{
|
||||
.usage = .storage,
|
||||
.target_queue = .graphics,
|
||||
.array_capacity = max_materials,
|
||||
.name = "Materials",
|
||||
});
|
||||
errdefer material_buffer.deinit();
|
||||
|
||||
// VOLATILE Synchronize with explicit values on top of `Id` type.
|
||||
|
||||
try material_buffer.write(.{
|
||||
.element_offset = Id.empty.toInt(),
|
||||
.elements = &.{
|
||||
.{
|
||||
.base_color = .zero,
|
||||
.emissive = .init(1, 0, 1),
|
||||
.ior = 1.45,
|
||||
.metallic = 0,
|
||||
.normal_scale = 1,
|
||||
.occlusion_texture_strength = 1,
|
||||
.roughness = 1,
|
||||
.base_color_texture = .empty_base_color,
|
||||
.emissive_texture = .empty_emissive,
|
||||
.normal_texture = .empty_normal,
|
||||
.occlusion_roughness_metallic_texture = .empty_occlusion_roughness_metallic,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return .{
|
||||
.map = map,
|
||||
.material_buffer = material_buffer,
|
||||
.material_count = @typeInfo(Id).@"enum".fields.len,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Materials) void {
|
||||
const allocator_general = ctx.allocator_general;
|
||||
|
||||
std.log.scoped(.deinit).debug("Deinitializing {*}", .{self});
|
||||
|
||||
self.material_buffer.deinit();
|
||||
self.map.deinit(allocator_general);
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
/// Get the ID of a material given its filename (as a string). Returns `null` if
|
||||
/// such material hasn't been loaded. Returns `.empty` when the filename is
|
||||
/// `null`.
|
||||
pub fn get(self: *const Materials, maybe_filename: ?[]const u8) ?Id {
|
||||
if (maybe_filename) |filename| {
|
||||
return self.map.get(.{
|
||||
// If the atom doesn't exist, then the material cannot possibly exist.
|
||||
.filename = .fromStringIfExists(filename) orelse return null,
|
||||
});
|
||||
} else {
|
||||
return .empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a material given its filename (as an atom). Returns `null` if
|
||||
/// such material hasn't been loaded. Returns `.empty` when the filename is
|
||||
/// `.empty`.
|
||||
pub fn getAtom(self: *const Materials, filename: Atom) ?Id {
|
||||
if (filename != .empty) {
|
||||
return self.map.get(.{
|
||||
.filename = filename,
|
||||
});
|
||||
} else {
|
||||
return .empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a material given its filename (as a string). Returns either an
|
||||
/// existing material ID or loads a new material along with its textures and
|
||||
/// assigns a new ID, if necessary. Will not return any error if the material
|
||||
/// already exists. Returns `.empty` when the filename is `null`.
|
||||
///
|
||||
/// When a material or its textures are being loaded, `temp_allocator` is used
|
||||
/// for temporary allocations necessary to perform all operations. No memory
|
||||
/// allocated with `temp_allocator` is retained, so the allocator can be
|
||||
/// deinitialized or reset after this function returns. Note that during loading
|
||||
/// the engine will make its own persistent allocations, so an out of memory
|
||||
/// error is not necessarily related to `temp_allocator`.
|
||||
pub fn getOrLoad(
|
||||
self: *Materials,
|
||||
textures: *Textures,
|
||||
stbi: *media.stbi,
|
||||
maybe_filename: ?[]const u8,
|
||||
) !Id {
|
||||
if (maybe_filename) |filename| {
|
||||
const key: Key = .{
|
||||
// If the material already exists, then the atom must exist and the
|
||||
// following line will not return any error.
|
||||
.filename = try .fromString(filename),
|
||||
};
|
||||
|
||||
// We don't use `getOrPutAssumeCapacity` method, because we might already be
|
||||
// at full capacity, in which case we should return `error.OutOfMaterials`.
|
||||
|
||||
if (self.map.get(key)) |id| {
|
||||
return id;
|
||||
} else {
|
||||
const id = Id.fromIndexSafe(self.material_count) catch |err| switch (err) {
|
||||
error.Overflow => return error.OutOfMaterials,
|
||||
};
|
||||
try self.loadMaterial(textures, stbi, filename, id.toInt());
|
||||
|
||||
self.map.putAssumeCapacityNoClobber(key, id);
|
||||
self.material_count += 1;
|
||||
|
||||
return id;
|
||||
}
|
||||
} else {
|
||||
return .empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a material given its filename (as an atom). Returns either an
|
||||
/// existing material ID or loads a new material along with its textures and
|
||||
/// assigns a new ID, if necessary. Will not return any error if the material
|
||||
/// already exists. Returns `.empty` when the filename is `.empty`.
|
||||
///
|
||||
/// When a material or its textures are being loaded, `temp_allocator` is used
|
||||
/// for temporary allocations necessary to perform all operations. No memory
|
||||
/// allocated with `temp_allocator` is retained, so the allocator can be
|
||||
/// deinitialized or reset after this function returns. Note that during loading
|
||||
/// the engine will make its own persistent allocations, so an out of memory
|
||||
/// error is not necessarily related to `temp_allocator`.
|
||||
pub fn getOrLoadAtom(
|
||||
self: *Materials,
|
||||
textures: *Textures,
|
||||
stbi: *media.stbi,
|
||||
filename: Atom,
|
||||
) !Id {
|
||||
if (filename != .empty) {
|
||||
const key: Key = .{
|
||||
.filename = filename,
|
||||
};
|
||||
|
||||
// We don't use `getOrPutAssumeCapacity` method, because we might already be
|
||||
// at full capacity, in which case we should return `error.OutOfMaterials`.
|
||||
|
||||
if (self.map.get(key)) |id| {
|
||||
return id;
|
||||
} else {
|
||||
const id = Id.fromIndexSafe(self.material_count) catch |err| switch (err) {
|
||||
error.Overflow => return error.OutOfMaterials,
|
||||
};
|
||||
try self.loadMaterial(textures, stbi, filename.toString(), id.toInt());
|
||||
|
||||
self.map.putAssumeCapacityNoClobber(key, id);
|
||||
self.material_count += 1;
|
||||
|
||||
return id;
|
||||
}
|
||||
} else {
|
||||
return .empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan the materials directory and load all materials that haven't been loaded
|
||||
/// already. Will not traverse subdirectories. Any errors will be skipped and
|
||||
/// logged.
|
||||
///
|
||||
/// When a material or its textures are being loaded, `temp_allocator` is used
|
||||
/// for temporary allocations necessary to perform all operations. No memory
|
||||
/// allocated with `temp_allocator` is retained, so the allocator can be
|
||||
/// deinitialized or reset after this function returns. Note that during loading
|
||||
/// the engine will make its own persistent allocations, so an out of memory
|
||||
/// error is not necessarily related to `temp_allocator`.
|
||||
pub fn loadAll(
|
||||
self: *Materials,
|
||||
textures: *Textures,
|
||||
stbi: *media.stbi,
|
||||
) void {
|
||||
const io = ctx.io;
|
||||
|
||||
const cwd = std.Io.Dir.cwd();
|
||||
|
||||
var dir = cwd.openDir(io, "assets/materials", .{ .iterate = true }) catch |err| {
|
||||
std.log.err("Error while opening metarials directory: {s}", .{@errorName(err)});
|
||||
return;
|
||||
};
|
||||
defer dir.close(io);
|
||||
|
||||
var it = dir.iterate();
|
||||
while (it.next() catch |err| {
|
||||
std.log.err("Error while iterating over materials directory: {s}", .{@errorName(err)});
|
||||
return;
|
||||
}) |entry| {
|
||||
if (entry.kind != .file) {
|
||||
std.log.warn("Skipping material entry {s}, which is not a file", .{entry.name});
|
||||
continue;
|
||||
}
|
||||
|
||||
_ = self.getOrLoad(textures, stbi, entry.name) catch |err| {
|
||||
std.log.err("Error while loading material entry {s}: {s}", .{ entry.name, @errorName(err) });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn loadMaterial(self: *Materials, textures: *Textures, stbi: *media.stbi, filename: []const u8, index: u32) !void {
|
||||
const allocator_frame = ctx.allocator_frame;
|
||||
const io = ctx.io;
|
||||
|
||||
const MaterialJson = struct {
|
||||
baseColor: [3]f32 = .{ 1, 1, 1 },
|
||||
baseColorTexture: ?[]const u8 = null,
|
||||
emissive: [3]f32 = .{ 0, 0, 0 },
|
||||
emissiveTexture: ?[]const u8 = null,
|
||||
ior: f32 = 1.45,
|
||||
metallic: f32 = 1,
|
||||
normalScale: f32 = 1,
|
||||
normalTexture: ?[]const u8 = null,
|
||||
occlusionRoughnessMetallicTexture: ?[]const u8 = null,
|
||||
occlusionTextureStrength: f32 = 1,
|
||||
roughness: f32 = 1,
|
||||
};
|
||||
|
||||
std.log.debug("Loading material \"{s}\"...", .{filename});
|
||||
|
||||
const cwd = std.Io.Dir.cwd();
|
||||
|
||||
var dir = try cwd.openDir(io, "assets/materials", .{});
|
||||
defer dir.close(io);
|
||||
|
||||
// NOTE Buffer size approximated based on expected JSON structure.
|
||||
var buffer: [512]u8 = undefined;
|
||||
|
||||
const file = try dir.openFile(io, filename, .{});
|
||||
defer file.close(io);
|
||||
|
||||
var file_reader = file.reader(io, &buffer);
|
||||
var json_reader = std.json.Reader.init(allocator_frame, &file_reader.interface);
|
||||
|
||||
const material_json = try std.json.parseFromTokenSourceLeaky(MaterialJson, allocator_frame, &json_reader, .{
|
||||
.duplicate_field_behavior = .@"error",
|
||||
.ignore_unknown_fields = false,
|
||||
.allocate = .alloc_if_needed,
|
||||
});
|
||||
|
||||
try self.material_buffer.write(.{
|
||||
.element_offset = index,
|
||||
.elements = &.{
|
||||
.{
|
||||
.base_color = .initArray(material_json.baseColor),
|
||||
.emissive = .initArray(material_json.emissive),
|
||||
.ior = material_json.ior,
|
||||
.metallic = material_json.metallic,
|
||||
.normal_scale = material_json.normalScale,
|
||||
.occlusion_texture_strength = material_json.occlusionTextureStrength,
|
||||
.roughness = material_json.roughness,
|
||||
.base_color_texture = try textures.getOrLoad(stbi, material_json.baseColorTexture, .base_color),
|
||||
.emissive_texture = try textures.getOrLoad(stbi, material_json.emissiveTexture, .emissive),
|
||||
.normal_texture = try textures.getOrLoad(stbi, material_json.normalTexture, .normal),
|
||||
.occlusion_roughness_metallic_texture = try textures.getOrLoad(stbi, material_json.occlusionRoughnessMetallicTexture, .occlusion_roughness_metallic),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
//! Module for loading persistent textures.
|
||||
|
||||
const Textures = @This();
|
||||
const std = @import("std");
|
||||
|
||||
const ctx = @import("../AppContext.zig");
|
||||
const media = @import("media");
|
||||
|
||||
const Atom = @import("../engine/Atom.zig").Atom;
|
||||
const Engine = @import("../engine/Engine.zig");
|
||||
const Texture = @import("../engine/Texture.zig");
|
||||
|
||||
pub const Id = enum(u16) {
|
||||
// VOLATILE Synchronize explicit values with `init` implementation.
|
||||
|
||||
/// 1×1 texture with usage `.base_color`, whose texel is read as `vec4(1)`.
|
||||
empty_base_color = 0,
|
||||
/// 1×1 texture with usage `.emissive`, whose texel is read as `vec4(1)`.
|
||||
empty_emissive = 1,
|
||||
/// 1×1 texture with usage `.normal`, whose texel is read as
|
||||
/// `vec4(0, 0, 1, 1)`.
|
||||
empty_normal = 2,
|
||||
/// 1×1 texture with usage `,occlusion_roughness_metallic`, whose texel is
|
||||
/// read as `vec4(1)`.
|
||||
empty_occlusion_roughness_metallic = 3,
|
||||
_,
|
||||
|
||||
/// Cast an integer into an ID. This can produce an invalid ID.
|
||||
pub fn fromInt(value: u16) Id {
|
||||
return @enumFromInt(value);
|
||||
}
|
||||
|
||||
/// Cast an index into an ID. This can produce an invalid ID. The caller
|
||||
/// asserts that the index is not greater than the max ID value.
|
||||
pub fn fromIndex(index: usize) Id {
|
||||
std.debug.assert(index < max_textures);
|
||||
return @enumFromInt(@as(u16, @intCast(index)));
|
||||
}
|
||||
|
||||
/// Cast an index into an ID. This can produce an invalid ID. Returns an
|
||||
/// error if the index is greater than the max ID value.
|
||||
pub fn fromIndexSafe(index: usize) error{Overflow}!Id {
|
||||
if (index >= max_textures) return error.Overflow;
|
||||
return @enumFromInt(@as(u16, @intCast(index)));
|
||||
}
|
||||
|
||||
/// Cast an ID into an integer.
|
||||
pub fn toInt(self: Id) u16 {
|
||||
return @intFromEnum(self);
|
||||
}
|
||||
};
|
||||
|
||||
pub const Key = struct {
|
||||
/// Atom representing the filename of the texture.
|
||||
filename: Atom,
|
||||
/// Desired usage of the texture.
|
||||
usage: Texture.Usage,
|
||||
};
|
||||
|
||||
/// Maps a key value to a texture ID. Preallocated with `allocator_general`.
|
||||
map: std.AutoHashMapUnmanaged(Key, Id),
|
||||
/// Stores all `Texture` structs and maps a texture ID to a `Texture` struct.
|
||||
/// Preallocated with `allocator_general`.
|
||||
array: std.ArrayList(Texture),
|
||||
|
||||
/// 4096 textures of usage `.base_color` and 16×16 dimensions should take 4 MiB
|
||||
/// in VRAM.
|
||||
pub const max_textures = 4096;
|
||||
|
||||
pub fn init() !Textures {
|
||||
const allocator_general = ctx.allocator_general;
|
||||
|
||||
var map: std.AutoHashMapUnmanaged(Key, Id) = .empty;
|
||||
errdefer map.deinit(allocator_general);
|
||||
try map.ensureTotalCapacity(allocator_general, max_textures);
|
||||
|
||||
var array: std.ArrayList(Texture) = try .initCapacity(allocator_general, max_textures);
|
||||
errdefer {
|
||||
for (array.items) |*texture| {
|
||||
texture.deinit();
|
||||
}
|
||||
array.deinit(allocator_general);
|
||||
}
|
||||
|
||||
// VOLATILE Synchronize with explicit values on top of `Id` type.
|
||||
|
||||
const empty_base_color_texture = try Texture.init(.{
|
||||
.width = 1,
|
||||
.height = 1,
|
||||
.usage = .base_color,
|
||||
.target_queue = .graphics,
|
||||
.name = "@Empty",
|
||||
});
|
||||
array.appendAssumeCapacity(empty_base_color_texture);
|
||||
|
||||
const empty_emissive_texture = try Texture.init(.{
|
||||
.width = 1,
|
||||
.height = 1,
|
||||
.usage = .emissive,
|
||||
.target_queue = .graphics,
|
||||
.name = "@Empty",
|
||||
});
|
||||
array.appendAssumeCapacity(empty_emissive_texture);
|
||||
|
||||
const empty_normal_texture = try Texture.init(.{
|
||||
.width = 1,
|
||||
.height = 1,
|
||||
.usage = .normal,
|
||||
.target_queue = .graphics,
|
||||
.name = "@Empty",
|
||||
});
|
||||
array.appendAssumeCapacity(empty_normal_texture);
|
||||
|
||||
const empty_occlusuion_roughness_metallic_texture = try Texture.init(.{
|
||||
.width = 1,
|
||||
.height = 1,
|
||||
.usage = .occlusion_roughness_metallic,
|
||||
.target_queue = .graphics,
|
||||
.name = "@Empty",
|
||||
});
|
||||
array.appendAssumeCapacity(empty_occlusuion_roughness_metallic_texture);
|
||||
|
||||
try empty_base_color_texture.writeSamples(u8, &.{ 255, 255, 255, 255 });
|
||||
try empty_emissive_texture.writeSamples(f16, &.{ 1.0, 1.0, 1.0, 1.0 });
|
||||
try empty_normal_texture.writeSamples(i8, &.{ 0, 0, 127, 127 });
|
||||
try empty_occlusuion_roughness_metallic_texture.writeSamples(u8, &.{ 255, 255, 255, 255 });
|
||||
|
||||
return .{
|
||||
.map = map,
|
||||
.array = array,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Textures) void {
|
||||
const allocator_general = ctx.allocator_general;
|
||||
|
||||
std.log.scoped(.deinit).debug("Deinitializing {*}", .{self});
|
||||
|
||||
for (self.array.items) |*texture| {
|
||||
texture.deinit();
|
||||
}
|
||||
self.array.deinit(allocator_general);
|
||||
self.map.deinit(allocator_general);
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
/// Get the ID of a texture given its filename (as a string) and usage. Returns
|
||||
/// `null` if such texture hasn't been loaded. When the filename is `null`,
|
||||
/// returns an empty texture ID appropriate for given usage.
|
||||
pub fn get(self: *const Textures, maybe_filename: ?[]const u8, usage: Texture.Usage) ?Id {
|
||||
if (maybe_filename) |filename| {
|
||||
return self.map.get(.{
|
||||
// If the atom doesn't exist, then the texture cannot possibly exist.
|
||||
.filename = .fromStringIfExists(filename) orelse return null,
|
||||
.usage = usage,
|
||||
});
|
||||
} else {
|
||||
return emptyTextureForUsage(usage);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a texture given its filename (as an atom) and usage. Returns
|
||||
/// `null` if such texture hasn't been loaded. When the filename is `.empty`,
|
||||
/// returns an empty texture ID appropriate for given usage.
|
||||
pub fn getAtom(self: *const Textures, filename: Atom, usage: Texture.Usage) ?Id {
|
||||
if (filename != .empty) {
|
||||
return self.map.get(.{
|
||||
.filename = filename,
|
||||
.usage = usage,
|
||||
});
|
||||
} else {
|
||||
return emptyTextureForUsage(usage);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a texture given its filename (as a string) and usage. Returns
|
||||
/// either an existing texture ID or loads a new texture and assigns a new ID,
|
||||
/// if necessary. Will not return any error if the texture already exists. When
|
||||
/// the filename is `null`, returns an empty texture ID appropriate for given
|
||||
/// usage.
|
||||
pub fn getOrLoad(
|
||||
self: *Textures,
|
||||
stbi: *media.stbi,
|
||||
maybe_filename: ?[]const u8,
|
||||
usage: Texture.Usage,
|
||||
) !Id {
|
||||
if (maybe_filename) |filename| {
|
||||
const key: Key = .{
|
||||
// If the texture already exists, then the atom must exist and the
|
||||
// following line will not return any error.
|
||||
.filename = try .fromString(filename),
|
||||
.usage = usage,
|
||||
};
|
||||
|
||||
// We don't use `getOrPutAssumeCapacity` method, because we might already be
|
||||
// at full capacity, in which case we should return `error.OutOfTextures`.
|
||||
|
||||
if (self.map.get(key)) |id| {
|
||||
return id;
|
||||
} else {
|
||||
const id = Id.fromIndexSafe(self.array.items.len) catch |err| switch (err) {
|
||||
error.Overflow => return error.OutOfTextures,
|
||||
};
|
||||
const texture = try loadTexture(stbi, filename, usage);
|
||||
|
||||
self.map.putAssumeCapacityNoClobber(key, id);
|
||||
self.array.appendAssumeCapacity(texture);
|
||||
|
||||
return id;
|
||||
}
|
||||
} else {
|
||||
return emptyTextureForUsage(usage);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of a texture given its filename (as an atom) and usage. Returns
|
||||
/// either an existing texture ID or loads a new texture and assigns a new ID,
|
||||
/// if necessary. Will not return any error if the texture already exists. When
|
||||
/// the filename is `.empty`, returns an empty texture ID appropriate for given
|
||||
/// usage.
|
||||
pub fn getOrLoadAtom(
|
||||
self: *Textures,
|
||||
stbi: *media.stbi,
|
||||
filename: Atom,
|
||||
usage: Texture.Usage,
|
||||
) !Id {
|
||||
if (filename != .empty) {
|
||||
const key: Key = .{
|
||||
.filename = filename,
|
||||
.usage = usage,
|
||||
};
|
||||
|
||||
// We don't use `getOrPutAssumeCapacity` method, because we might already be
|
||||
// at full capacity, in which case we should return `error.OutOfTextures`.
|
||||
|
||||
if (self.map.get(key)) |id| {
|
||||
return id;
|
||||
} else {
|
||||
const id = Id.fromIndexSafe(self.array.items.len) catch |err| switch (err) {
|
||||
error.Overflow => return error.OutOfTextures,
|
||||
};
|
||||
const texture = try loadTexture(stbi, filename.toString(), usage);
|
||||
|
||||
self.map.putAssumeCapacityNoClobber(key, id);
|
||||
self.array.appendAssumeCapacity(texture);
|
||||
|
||||
return id;
|
||||
}
|
||||
} else {
|
||||
return emptyTextureForUsage(usage);
|
||||
}
|
||||
}
|
||||
|
||||
fn loadTexture(
|
||||
stbi: *media.stbi,
|
||||
filename: []const u8,
|
||||
usage: Texture.Usage,
|
||||
) !Texture {
|
||||
const io = ctx.io;
|
||||
|
||||
std.log.debug("Loading texture \"{s}\" as {s}...", .{ filename, @tagName(usage) });
|
||||
|
||||
const cwd = std.Io.Dir.cwd();
|
||||
|
||||
var dir = try cwd.openDir(io, "assets/textures", .{});
|
||||
defer dir.close(io);
|
||||
|
||||
var file = try dir.openFile(io, filename, .{});
|
||||
defer file.close(io);
|
||||
|
||||
// The textures are expected to be small; a standard block base color as a
|
||||
// PNG takes well below 1 kiB.
|
||||
var buf: [4096]u8 = undefined;
|
||||
var reader = file.reader(io, &buf);
|
||||
|
||||
const img = try stbi.loadDynamicIo(&reader.interface);
|
||||
defer stbi.freeDynamic(img);
|
||||
|
||||
const data = img.data[0 .. img.width * img.height];
|
||||
|
||||
if (usage == .normal) {
|
||||
for (data) |*pixel| {
|
||||
pixel.r = pixel.r +% 128;
|
||||
pixel.g = pixel.g +% 128;
|
||||
pixel.b = pixel.b +% 128;
|
||||
pixel.a = pixel.a +% 128;
|
||||
}
|
||||
}
|
||||
|
||||
var texture = try Texture.init(.{
|
||||
.width = img.width,
|
||||
.height = img.height,
|
||||
.usage = usage,
|
||||
.target_queue = .graphics,
|
||||
.name = filename,
|
||||
});
|
||||
errdefer texture.deinit();
|
||||
|
||||
try texture.writeRaw(@ptrCast(data));
|
||||
return texture;
|
||||
}
|
||||
|
||||
fn emptyTextureForUsage(usage: Texture.Usage) !Id {
|
||||
return switch (usage) {
|
||||
.base_color => .empty_base_color,
|
||||
.normal => .empty_normal,
|
||||
.occlusion_roughness_metallic => .empty_occlusion_roughness_metallic,
|
||||
.emissive => .empty_emissive,
|
||||
.depth => error.InvalidUsage,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user