update to latest mach-core API

This commit is contained in:
Ali Chraghi 2023-08-03 06:07:27 +03:30 committed by Stephen Gutekanst
parent 2288073366
commit c26cfec0b6
7 changed files with 70 additions and 81 deletions

@ -1 +1 @@
Subproject commit 0e827426c604e35e502d11b1daaf5359bccaf20c Subproject commit 0d11b2e042855ccc5a8aea5bd5a1114e4b902b6d

@ -1 +1 @@
Subproject commit cde799d26a2345931e77e0502fc0c36ccd905c00 Subproject commit 54c614d6191279d4b2c65c8097aa985ff163ee93

@ -1 +1 @@
Subproject commit ad9f4e77a4db6d5e2e635e45db8878eaf7945a88 Subproject commit c80eb83f9fe99d68a01508108e424c3c41ce9bf8

View file

@ -1,8 +1,10 @@
const std = @import("std"); const std = @import("std");
const mach = @import("mach"); const mach = @import("mach");
const core = mach.core;
const gpu = mach.gpu; const gpu = mach.gpu;
pub const App = @This(); pub const name = .editor;
pub const App = mach.App(.{ mach.Module, @This() });
const UniformBufferObject = struct { const UniformBufferObject = struct {
resolution: @Vector(2, f32), resolution: @Vector(2, f32),
@ -12,7 +14,6 @@ const UniformBufferObject = struct {
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator(); const allocator = gpa.allocator();
core: mach.Core,
timer: mach.Timer, timer: mach.Timer,
pipeline: *gpu.RenderPipeline, pipeline: *gpu.RenderPipeline,
queue: *gpu.Queue, queue: *gpu.Queue,
@ -23,8 +24,10 @@ fragment_shader_file: std.fs.File,
fragment_shader_code: [:0]const u8, fragment_shader_code: [:0]const u8,
last_mtime: i128, last_mtime: i128,
pub fn init(app: *App) !void { pub fn init(adapter: anytype) !void {
try app.core.init(allocator, .{ .title = "Mach editor" }); var editor = adapter.mod(.editor).state();
core.setTitle("Mach editor");
var fragment_file: std.fs.File = undefined; var fragment_file: std.fs.File = undefined;
var last_mtime: i128 = undefined; var last_mtime: i128 = undefined;
@ -44,19 +47,19 @@ pub fn init(app: *App) !void {
} }
var code = try fragment_file.readToEndAllocOptions(allocator, std.math.maxInt(u16), null, 1, 0); var code = try fragment_file.readToEndAllocOptions(allocator, std.math.maxInt(u16), null, 1, 0);
const queue = app.core.device().getQueue(); const queue = core.device.getQueue();
// We need a bgl to bind the UniformBufferObject, but it is also needed for creating // We need a bgl to bind the UniformBufferObject, but it is also needed for creating
// the RenderPipeline, so we pass it to recreatePipeline as a pointer // the RenderPipeline, so we pass it to recreatePipeline as a pointer
var bgl: *gpu.BindGroupLayout = undefined; var bgl: *gpu.BindGroupLayout = undefined;
const pipeline = recreatePipeline(&app.core, code, &bgl); const pipeline = recreatePipeline(code, &bgl);
const uniform_buffer = app.core.device().createBuffer(&.{ const uniform_buffer = core.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true }, .usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(UniformBufferObject), .size = @sizeOf(UniformBufferObject),
.mapped_at_creation = false, .mapped_at_creation = false,
}); });
const bind_group = app.core.device().createBindGroup( const bind_group = core.device.createBindGroup(
&gpu.BindGroup.Descriptor.init(.{ &gpu.BindGroup.Descriptor.init(.{
.layout = bgl, .layout = bgl,
.entries = &.{ .entries = &.{
@ -65,59 +68,61 @@ pub fn init(app: *App) !void {
}), }),
); );
app.timer = try mach.Timer.start(); editor.timer = try mach.Timer.start();
app.pipeline = pipeline; editor.pipeline = pipeline;
app.queue = queue; editor.queue = queue;
app.uniform_buffer = uniform_buffer; editor.uniform_buffer = uniform_buffer;
app.bind_group = bind_group; editor.bind_group = bind_group;
app.fragment_shader_file = fragment_file; editor.fragment_shader_file = fragment_file;
app.fragment_shader_code = code; editor.fragment_shader_code = code;
app.last_mtime = last_mtime; editor.last_mtime = last_mtime;
bgl.release(); bgl.release();
} }
pub fn deinit(app: *App) void { pub fn deinit(adapter: anytype) !void {
var editor = adapter.mod(.editor).state();
defer _ = gpa.deinit(); defer _ = gpa.deinit();
defer app.core.deinit();
app.fragment_shader_file.close(); editor.fragment_shader_file.close();
allocator.free(app.fragment_shader_code); allocator.free(editor.fragment_shader_code);
app.uniform_buffer.release(); editor.uniform_buffer.release();
app.bind_group.release(); editor.bind_group.release();
} }
pub fn update(app: *App) !bool { pub fn tick(adapter: anytype) !void {
var iter = app.core.pollEvents(); var editor = adapter.mod(.editor).state();
var iter = core.pollEvents();
while (iter.next()) |event| { while (iter.next()) |event| {
switch (event) { switch (event) {
.key_press => |ev| { .key_press => |ev| {
if (ev.key == .space) return true; if (ev.key == .space) return adapter.send(.machExit);
}, },
.close => return true, .close => return adapter.send(.machExit),
else => {}, else => {},
} }
} }
if (app.fragment_shader_file.stat()) |stat| { if (editor.fragment_shader_file.stat()) |stat| {
if (app.last_mtime < stat.mtime) { if (editor.last_mtime < stat.mtime) {
std.log.info("The fragment shader has been changed", .{}); std.log.info("The fragment shader has been changed", .{});
app.last_mtime = stat.mtime; editor.last_mtime = stat.mtime;
app.fragment_shader_file.seekTo(0) catch unreachable; editor.fragment_shader_file.seekTo(0) catch unreachable;
app.fragment_shader_code = app.fragment_shader_file.readToEndAllocOptions(allocator, std.math.maxInt(u32), null, 1, 0) catch |err| { editor.fragment_shader_code = editor.fragment_shader_file.readToEndAllocOptions(allocator, std.math.maxInt(u32), null, 1, 0) catch |err| {
std.log.err("Err: {}", .{err}); std.log.err("Err: {}", .{err});
return true; return adapter.send(.machExit);
}; };
app.pipeline = recreatePipeline(&app.core, app.fragment_shader_code, null); editor.pipeline = recreatePipeline(editor.fragment_shader_code, null);
} }
} else |err| { } else |err| {
std.log.err("Something went wrong when attempting to stat file: {}\n", .{err}); std.log.err("Something went wrong when attempting to stat file: {}\n", .{err});
} }
const back_buffer_view = app.core.swapChain().getCurrentTextureView().?; const back_buffer_view = core.swap_chain.getCurrentTextureView().?;
const color_attachment = gpu.RenderPassColorAttachment{ const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view, .view = back_buffer_view,
.clear_value = std.mem.zeroes(gpu.Color), .clear_value = std.mem.zeroes(gpu.Color),
@ -125,21 +130,21 @@ pub fn update(app: *App) !bool {
.store_op = .store, .store_op = .store,
}; };
const encoder = app.core.device().createCommandEncoder(null); const encoder = core.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassDescriptor.init(.{ const render_pass_info = gpu.RenderPassDescriptor.init(.{
.color_attachments = &.{color_attachment}, .color_attachments = &.{color_attachment},
}); });
const time = app.timer.read() / @as(f32, std.time.ns_per_s); const time = editor.timer.read() / @as(f32, std.time.ns_per_s);
const ubo = UniformBufferObject{ const ubo = UniformBufferObject{
.resolution = .{ @as(f32, @floatFromInt(app.core.descriptor().width)), @as(f32, @floatFromInt(app.core.descriptor().height)) }, .resolution = .{ @as(f32, @floatFromInt(core.descriptor.width)), @as(f32, @floatFromInt(core.descriptor.height)) },
.time = time, .time = time,
}; };
encoder.writeBuffer(app.uniform_buffer, 0, &[_]UniformBufferObject{ubo}); encoder.writeBuffer(editor.uniform_buffer, 0, &[_]UniformBufferObject{ubo});
const pass = encoder.beginRenderPass(&render_pass_info); const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(app.pipeline); pass.setPipeline(editor.pipeline);
pass.setBindGroup(0, app.bind_group, &.{0}); pass.setBindGroup(0, editor.bind_group, &.{0});
pass.draw(3, 1, 0, 0); pass.draw(3, 1, 0, 0);
pass.end(); pass.end();
pass.release(); pass.release();
@ -147,25 +152,23 @@ pub fn update(app: *App) !bool {
var command = encoder.finish(null); var command = encoder.finish(null);
encoder.release(); encoder.release();
app.queue.submit(&[_]*gpu.CommandBuffer{command}); editor.queue.submit(&[_]*gpu.CommandBuffer{command});
command.release(); command.release();
app.core.swapChain().present(); core.swap_chain.present();
back_buffer_view.release(); back_buffer_view.release();
return false;
} }
fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?**gpu.BindGroupLayout) *gpu.RenderPipeline { fn recreatePipeline(fragment_shader_code: [:0]const u8, bgl: ?**gpu.BindGroupLayout) *gpu.RenderPipeline {
const vs_module = core.device().createShaderModuleWGSL("vert.wgsl", @embedFile("vert.wgsl")); const vs_module = core.device.createShaderModuleWGSL("vert.wgsl", @embedFile("vert.wgsl"));
defer vs_module.release(); defer vs_module.release();
// Check wether the fragment shader code compiled successfully, if not // Check wether the fragment shader code compiled successfully, if not
// print the validation layer error and show a black screen // print the validation layer error and show a black screen
core.device().pushErrorScope(.validation); core.device.pushErrorScope(.validation);
var fs_module = core.device().createShaderModuleWGSL("fragment shader", fragment_shader_code); var fs_module = core.device.createShaderModuleWGSL("fragment shader", fragment_shader_code);
var error_occurred: bool = false; var error_occurred: bool = false;
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?) // popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = core.device().popErrorScope(&error_occurred, struct { _ = core.device.popErrorScope(&error_occurred, struct {
inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void { inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .no_error) { if (typ != .no_error) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message}); std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
@ -174,7 +177,7 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
} }
}.callback); }.callback);
if (error_occurred) { if (error_occurred) {
fs_module = core.device().createShaderModuleWGSL( fs_module = core.device.createShaderModuleWGSL(
"black_screen_frag.wgsl", "black_screen_frag.wgsl",
@embedFile("black_screen_frag.wgsl"), @embedFile("black_screen_frag.wgsl"),
); );
@ -183,7 +186,7 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
const blend = gpu.BlendState{}; const blend = gpu.BlendState{};
const color_target = gpu.ColorTargetState{ const color_target = gpu.ColorTargetState{
.format = core.descriptor().format, .format = core.descriptor.format,
.blend = &blend, .blend = &blend,
.write_mask = gpu.ColorWriteMaskFlags.all, .write_mask = gpu.ColorWriteMaskFlags.all,
}; };
@ -195,7 +198,7 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .fragment = true }, .uniform, true, 0); const bgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .fragment = true }, .uniform, true, 0);
// bgl is needed outside, for the creation of the uniform_buffer in main // bgl is needed outside, for the creation of the uniform_buffer in main
const bgl_tmp = core.device().createBindGroupLayout(&gpu.BindGroupLayout.Descriptor.init(.{ const bgl_tmp = core.device.createBindGroupLayout(&gpu.BindGroupLayout.Descriptor.init(.{
.entries = &.{bgle}, .entries = &.{bgle},
})); }));
defer { defer {
@ -208,7 +211,7 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
} }
const bind_group_layouts = [_]*gpu.BindGroupLayout{bgl_tmp}; const bind_group_layouts = [_]*gpu.BindGroupLayout{bgl_tmp};
const pipeline_layout = core.device().createPipelineLayout(&gpu.PipelineLayout.Descriptor.init(.{ const pipeline_layout = core.device.createPipelineLayout(&gpu.PipelineLayout.Descriptor.init(.{
.bind_group_layouts = &bind_group_layouts, .bind_group_layouts = &bind_group_layouts,
})); }));
defer pipeline_layout.release(); defer pipeline_layout.release();
@ -224,10 +227,10 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
// Create the render pipeline. Even if the shader compilation succeeded, this could fail if the // Create the render pipeline. Even if the shader compilation succeeded, this could fail if the
// shader is missing a `main` entrypoint. // shader is missing a `main` entrypoint.
core.device().pushErrorScope(.validation); core.device.pushErrorScope(.validation);
const pipeline = core.device().createRenderPipeline(&pipeline_descriptor); const pipeline = core.device.createRenderPipeline(&pipeline_descriptor);
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?) // popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
_ = core.device().popErrorScope(&error_occurred, struct { _ = core.device.popErrorScope(&error_occurred, struct {
inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void { inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
if (typ != .no_error) { if (typ != .no_error) {
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message}); std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
@ -237,7 +240,7 @@ fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?
}.callback); }.callback);
if (error_occurred) { if (error_occurred) {
// Retry with black_screen_frag which we know will work. // Retry with black_screen_frag which we know will work.
return recreatePipeline(core, @embedFile("black_screen_frag.wgsl"), bgl); return recreatePipeline(@embedFile("black_screen_frag.wgsl"), bgl);
} }
return pipeline; return pipeline;
} }

View file

@ -39,7 +39,7 @@ pub fn main() !void {
defer app.deinit(); defer app.deinit();
while (true) { while (true) {
if (try app.core.internal.update(&app)) return; if (try core.update(&app)) return;
} }
} }

View file

@ -1,6 +1,5 @@
const Core = @import("core").Core; const core = @import("core");
const gpu = @import("core").gpu; const gpu = @import("core").gpu;
const std = @import("std"); const std = @import("std");
const ecs = @import("ecs"); const ecs = @import("ecs");
@ -9,8 +8,6 @@ const allocator = gpa.allocator();
/// The main Mach engine ECS module. /// The main Mach engine ECS module.
pub const Module = struct { pub const Module = struct {
_core: Core,
core: *Core,
device: *gpu.Device, device: *gpu.Device,
exit: bool, exit: bool,
@ -19,32 +16,22 @@ pub const Module = struct {
pub fn machInit(adapter: anytype) !void { pub fn machInit(adapter: anytype) !void {
var mach = adapter.mod(.mach); var mach = adapter.mod(.mach);
mach.initState(.{ core.allocator = allocator;
._core = undefined, try core.init(.{});
.core = undefined, mach.state().exit = false;
.device = undefined,
.exit = false,
});
var state = mach.state();
try state._core.init(allocator, .{});
state.core = &state._core;
state.device = state.core.device();
try adapter.send(.init); try adapter.send(.init);
} }
pub fn machDeinit(adapter: anytype) !void { pub fn machDeinit(adapter: anytype) !void {
try adapter.send(.deinit); try adapter.send(.deinit);
core.deinit();
var state = adapter.mod(.mach).state();
state.core.deinit();
adapter.deinit(); adapter.deinit();
_ = gpa.deinit(); _ = gpa.deinit();
} }
pub fn machExit(adapter: anytype) !void { pub fn machExit(adapter: anytype) !void {
try adapter.send(.exit); try adapter.send(.exit);
var state = adapter.mod(.mach).state(); var state = adapter.mod(.mach).state();
state.exit = true; state.exit = true;
} }

View file

@ -1,8 +1,7 @@
const core = @import("core"); pub const core = @import("core");
pub const GPUInterface = core.GPUInterface; pub const GPUInterface = core.GPUInterface;
pub const scope_levels = core.scope_levels; pub const scope_levels = core.scope_levels;
pub const log_level = core.log_level; pub const log_level = core.log_level;
pub const Core = core.Core;
pub const Timer = core.Timer; pub const Timer = core.Timer;
pub const gpu = core.gpu; pub const gpu = core.gpu;