editor: fold shaderexp into editor
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
parent
a3ec0fb7a9
commit
4c34a65020
14 changed files with 47 additions and 226 deletions
|
|
@ -2,7 +2,7 @@ const std = @import("std");
|
|||
const mime_map = @import("Builder/mime.zig").mime_map;
|
||||
const Target = @import("target.zig").Target;
|
||||
const OptimizeMode = std.builtin.OptimizeMode;
|
||||
const allocator = @import("entrypoint.zig").allocator;
|
||||
const allocator = @import("main.zig").allocator;
|
||||
|
||||
const Builder = @This();
|
||||
|
||||
|
|
|
|||
243
src/editor/app.zig
Executable file
243
src/editor/app.zig
Executable file
|
|
@ -0,0 +1,243 @@
|
|||
const std = @import("std");
|
||||
const mach = @import("mach");
|
||||
const gpu = mach.gpu;
|
||||
|
||||
pub const App = @This();
|
||||
|
||||
const UniformBufferObject = struct {
|
||||
resolution: @Vector(2, f32),
|
||||
time: f32,
|
||||
};
|
||||
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
core: mach.Core,
|
||||
timer: mach.Timer,
|
||||
pipeline: *gpu.RenderPipeline,
|
||||
queue: *gpu.Queue,
|
||||
uniform_buffer: *gpu.Buffer,
|
||||
bind_group: *gpu.BindGroup,
|
||||
|
||||
fragment_shader_file: std.fs.File,
|
||||
fragment_shader_code: [:0]const u8,
|
||||
last_mtime: i128,
|
||||
|
||||
pub fn init(app: *App) !void {
|
||||
try app.core.init(allocator, .{ .title = "Mach editor" });
|
||||
|
||||
var fragment_file: std.fs.File = undefined;
|
||||
var last_mtime: i128 = undefined;
|
||||
|
||||
// TODO: there is no guarantee we are in the mach project root
|
||||
if (std.fs.cwd().openFile("src/editor/frag.wgsl", .{ .mode = .read_only })) |file| {
|
||||
fragment_file = file;
|
||||
if (file.stat()) |stat| {
|
||||
last_mtime = stat.mtime;
|
||||
} else |err| {
|
||||
std.debug.print("Something went wrong when attempting to stat file: {}\n", .{err});
|
||||
return;
|
||||
}
|
||||
} else |e| {
|
||||
std.debug.print("Something went wrong when attempting to open file: {}\n", .{e});
|
||||
return;
|
||||
}
|
||||
var code = try fragment_file.readToEndAllocOptions(allocator, std.math.maxInt(u16), null, 1, 0);
|
||||
|
||||
const queue = app.core.device().getQueue();
|
||||
|
||||
// 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
|
||||
var bgl: *gpu.BindGroupLayout = undefined;
|
||||
const pipeline = recreatePipeline(&app.core, code, &bgl);
|
||||
|
||||
const uniform_buffer = app.core.device().createBuffer(&.{
|
||||
.usage = .{ .copy_dst = true, .uniform = true },
|
||||
.size = @sizeOf(UniformBufferObject),
|
||||
.mapped_at_creation = false,
|
||||
});
|
||||
const bind_group = app.core.device().createBindGroup(
|
||||
&gpu.BindGroup.Descriptor.init(.{
|
||||
.layout = bgl,
|
||||
.entries = &.{
|
||||
gpu.BindGroup.Entry.buffer(0, uniform_buffer, 0, @sizeOf(UniformBufferObject)),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
app.timer = try mach.Timer.start();
|
||||
|
||||
app.pipeline = pipeline;
|
||||
app.queue = queue;
|
||||
app.uniform_buffer = uniform_buffer;
|
||||
app.bind_group = bind_group;
|
||||
|
||||
app.fragment_shader_file = fragment_file;
|
||||
app.fragment_shader_code = code;
|
||||
app.last_mtime = last_mtime;
|
||||
|
||||
bgl.release();
|
||||
}
|
||||
|
||||
pub fn deinit(app: *App) void {
|
||||
defer _ = gpa.deinit();
|
||||
defer app.core.deinit();
|
||||
|
||||
app.fragment_shader_file.close();
|
||||
allocator.free(app.fragment_shader_code);
|
||||
|
||||
app.uniform_buffer.release();
|
||||
app.bind_group.release();
|
||||
}
|
||||
|
||||
pub fn update(app: *App) !bool {
|
||||
var iter = app.core.pollEvents();
|
||||
while (iter.next()) |event| {
|
||||
switch (event) {
|
||||
.key_press => |ev| {
|
||||
if (ev.key == .space) return true;
|
||||
},
|
||||
.close => return true,
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
if (app.fragment_shader_file.stat()) |stat| {
|
||||
if (app.last_mtime < stat.mtime) {
|
||||
std.log.info("The fragment shader has been changed", .{});
|
||||
app.last_mtime = stat.mtime;
|
||||
app.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| {
|
||||
std.log.err("Err: {}", .{err});
|
||||
return true;
|
||||
};
|
||||
app.pipeline = recreatePipeline(&app.core, app.fragment_shader_code, null);
|
||||
}
|
||||
} else |err| {
|
||||
std.log.err("Something went wrong when attempting to stat file: {}\n", .{err});
|
||||
}
|
||||
|
||||
const back_buffer_view = app.core.swapChain().getCurrentTextureView().?;
|
||||
const color_attachment = gpu.RenderPassColorAttachment{
|
||||
.view = back_buffer_view,
|
||||
.clear_value = std.mem.zeroes(gpu.Color),
|
||||
.load_op = .clear,
|
||||
.store_op = .store,
|
||||
};
|
||||
|
||||
const encoder = app.core.device().createCommandEncoder(null);
|
||||
const render_pass_info = gpu.RenderPassDescriptor.init(.{
|
||||
.color_attachments = &.{color_attachment},
|
||||
});
|
||||
|
||||
const time = app.timer.read() / @as(f32, std.time.ns_per_s);
|
||||
const ubo = UniformBufferObject{
|
||||
.resolution = .{ @as(f32, @floatFromInt(app.core.descriptor().width)), @as(f32, @floatFromInt(app.core.descriptor().height)) },
|
||||
.time = time,
|
||||
};
|
||||
encoder.writeBuffer(app.uniform_buffer, 0, &[_]UniformBufferObject{ubo});
|
||||
|
||||
const pass = encoder.beginRenderPass(&render_pass_info);
|
||||
pass.setPipeline(app.pipeline);
|
||||
pass.setBindGroup(0, app.bind_group, &.{0});
|
||||
pass.draw(3, 1, 0, 0);
|
||||
pass.end();
|
||||
pass.release();
|
||||
|
||||
var command = encoder.finish(null);
|
||||
encoder.release();
|
||||
|
||||
app.queue.submit(&[_]*gpu.CommandBuffer{command});
|
||||
command.release();
|
||||
app.core.swapChain().present();
|
||||
back_buffer_view.release();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
fn recreatePipeline(core: *mach.Core, fragment_shader_code: [:0]const u8, bgl: ?**gpu.BindGroupLayout) *gpu.RenderPipeline {
|
||||
const vs_module = core.device().createShaderModuleWGSL("vert.wgsl", @embedFile("vert.wgsl"));
|
||||
defer vs_module.release();
|
||||
|
||||
// Check wether the fragment shader code compiled successfully, if not
|
||||
// print the validation layer error and show a black screen
|
||||
core.device().pushErrorScope(.validation);
|
||||
var fs_module = core.device().createShaderModuleWGSL("fragment shader", fragment_shader_code);
|
||||
var error_occurred: bool = false;
|
||||
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
|
||||
_ = core.device().popErrorScope(&error_occurred, struct {
|
||||
inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
|
||||
if (typ != .no_error) {
|
||||
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
|
||||
ctx.* = true;
|
||||
}
|
||||
}
|
||||
}.callback);
|
||||
if (error_occurred) {
|
||||
fs_module = core.device().createShaderModuleWGSL(
|
||||
"black_screen_frag.wgsl",
|
||||
@embedFile("black_screen_frag.wgsl"),
|
||||
);
|
||||
}
|
||||
defer fs_module.release();
|
||||
|
||||
const blend = gpu.BlendState{};
|
||||
const color_target = gpu.ColorTargetState{
|
||||
.format = core.descriptor().format,
|
||||
.blend = &blend,
|
||||
.write_mask = gpu.ColorWriteMaskFlags.all,
|
||||
};
|
||||
const fragment = gpu.FragmentState.init(.{
|
||||
.module = fs_module,
|
||||
.entry_point = "main",
|
||||
.targets = &.{color_target},
|
||||
});
|
||||
|
||||
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
|
||||
const bgl_tmp = core.device().createBindGroupLayout(&gpu.BindGroupLayout.Descriptor.init(.{
|
||||
.entries = &.{bgle},
|
||||
}));
|
||||
defer {
|
||||
// In frame we don't need to use bgl, so we can release it inside this function, else we pass bgl
|
||||
if (bgl == null) {
|
||||
bgl_tmp.release();
|
||||
} else {
|
||||
bgl.?.* = bgl_tmp;
|
||||
}
|
||||
}
|
||||
|
||||
const bind_group_layouts = [_]*gpu.BindGroupLayout{bgl_tmp};
|
||||
const pipeline_layout = core.device().createPipelineLayout(&gpu.PipelineLayout.Descriptor.init(.{
|
||||
.bind_group_layouts = &bind_group_layouts,
|
||||
}));
|
||||
defer pipeline_layout.release();
|
||||
|
||||
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
|
||||
.fragment = &fragment,
|
||||
.layout = pipeline_layout,
|
||||
.vertex = gpu.VertexState.init(.{
|
||||
.module = vs_module,
|
||||
.entry_point = "main",
|
||||
}),
|
||||
};
|
||||
|
||||
// Create the render pipeline. Even if the shader compilation succeeded, this could fail if the
|
||||
// shader is missing a `main` entrypoint.
|
||||
core.device().pushErrorScope(.validation);
|
||||
const pipeline = core.device().createRenderPipeline(&pipeline_descriptor);
|
||||
// popErrorScope() returns always true, (unless maybe it fails to capture the error scope?)
|
||||
_ = core.device().popErrorScope(&error_occurred, struct {
|
||||
inline fn callback(ctx: *bool, typ: gpu.ErrorType, message: [*:0]const u8) void {
|
||||
if (typ != .no_error) {
|
||||
std.debug.print("🔴🔴🔴🔴:\n{s}\n", .{message});
|
||||
ctx.* = true;
|
||||
}
|
||||
}
|
||||
}.callback);
|
||||
if (error_occurred) {
|
||||
// Retry with black_screen_frag which we know will work.
|
||||
return recreatePipeline(core, @embedFile("black_screen_frag.wgsl"), bgl);
|
||||
}
|
||||
return pipeline;
|
||||
}
|
||||
11
src/editor/black_screen_frag.wgsl
Executable file
11
src/editor/black_screen_frag.wgsl
Executable file
|
|
@ -0,0 +1,11 @@
|
|||
struct UniformBufferObject {
|
||||
time: f32,
|
||||
resolution: vec2<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> ubo : UniformBufferObject;
|
||||
|
||||
@fragment fn main(
|
||||
@location(0) uv : vec2<f32>
|
||||
) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>( 0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
94
src/editor/frag.wgsl
Executable file
94
src/editor/frag.wgsl
Executable file
|
|
@ -0,0 +1,94 @@
|
|||
struct UniformBufferObject {
|
||||
resolution: vec2<f32>,
|
||||
time: f32,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> ubo : UniformBufferObject;
|
||||
|
||||
fn getDist(p:vec3<f32>) -> f32{
|
||||
let dist_from_center:f32 = 2.*sin(ubo.time * 3.);
|
||||
let rotation_speed:f32 = 6.;
|
||||
|
||||
let sphere1 = vec4<f32>(dist_from_center*cos(rotation_speed*ubo.time + 3.14159 * 0. * 2. / 3.),1.1, dist_from_center*sin(rotation_speed*ubo.time + 3.14159 + 3.14159 * 0. * 2. / 3.),1.);
|
||||
let sphere2 = vec4<f32>(dist_from_center*cos(rotation_speed*ubo.time + 3.14159 * 1. * 2. / 3.),1.1, dist_from_center*sin(rotation_speed*ubo.time + 3.14159 + 3.14159 * 1. * 2. / 3.),1.);
|
||||
let sphere3 = vec4<f32>(dist_from_center*cos(rotation_speed*ubo.time + 3.14159 * 2. * 2. / 3.),1.1, dist_from_center*sin(rotation_speed*ubo.time + 3.14159 + 3.14159 * 2. * 2. / 3.),1.);
|
||||
|
||||
let sphere1_dist:f32 = length(p - sphere1.xyz) - sphere1.w;
|
||||
let sphere2_dist:f32 = length(p - sphere2.xyz) - sphere2.w;
|
||||
let sphere3_dist:f32 = length(p - sphere3.xyz) - sphere3.w;
|
||||
let plane_dist = p.y;
|
||||
|
||||
return min(min(min(sphere1_dist,sphere2_dist),sphere3_dist),plane_dist);
|
||||
}
|
||||
|
||||
fn rayMarch(ro:vec3<f32>, rd:vec3<f32>) -> f32{
|
||||
let MAX_STEPS:i32 = 100;
|
||||
let MAX_DIST:f32 = 100.0;
|
||||
let SURF_DIST:f32 = 0.01;
|
||||
var d:f32 = 0.0;
|
||||
|
||||
var i: i32 = 0;
|
||||
loop {
|
||||
if(i >= MAX_STEPS){
|
||||
break;
|
||||
}
|
||||
|
||||
let p = ro + rd * d;
|
||||
let ds = getDist(p);
|
||||
d = d + ds;
|
||||
if(d > MAX_DIST || ds <= SURF_DIST){
|
||||
break;
|
||||
}
|
||||
|
||||
i = i + 1;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
fn getNormal(p:vec3<f32>) -> vec3<f32>{
|
||||
let d = getDist(p);
|
||||
let e = vec2<f32>(0.1,0.0);
|
||||
|
||||
// We can find the normal using the points around the hit point
|
||||
let n = d - vec3<f32>(
|
||||
getDist(p-e.xyy),
|
||||
getDist(p-e.yxy),
|
||||
getDist(p-e.yyx)
|
||||
);
|
||||
|
||||
return normalize(n);
|
||||
}
|
||||
|
||||
fn getLight(p:vec3<f32>) -> f32{
|
||||
let SURF_DIST:f32 = .01;
|
||||
|
||||
let light_pos = vec3<f32>(0.,5.,0.);
|
||||
let l = normalize(light_pos - p) * 1.;
|
||||
let n = getNormal(p);
|
||||
|
||||
var dif = clamp(dot(n,l),.0,1.);
|
||||
|
||||
let d = rayMarch(p + n * SURF_DIST * 2.,l);
|
||||
if(d<length(light_pos - p)){
|
||||
dif = dif * .1;
|
||||
}
|
||||
|
||||
return dif;
|
||||
}
|
||||
|
||||
@fragment fn main(
|
||||
@location(0) uv : vec2<f32>
|
||||
) -> @location(0) vec4<f32> {
|
||||
let aspect = ubo.resolution / min(ubo.resolution.x,ubo.resolution.y);
|
||||
let tmp_uv = (uv - vec2(0.5,0.5)) * aspect * 2.0;
|
||||
var col = vec3<f32>(0.0);
|
||||
|
||||
let r_origin = vec3<f32>(4.0,3.,.0);
|
||||
let r_dir = normalize(vec3<f32>(-1.0,tmp_uv.y,tmp_uv.x));
|
||||
let d = rayMarch(r_origin,r_dir);
|
||||
col = vec3<f32>(d / 8.);
|
||||
let p = r_origin + r_dir * d;
|
||||
let diff = getLight(p);
|
||||
|
||||
col = vec3<f32>(0.0, diff, 0.0);
|
||||
return vec4<f32>(col,0.0);
|
||||
}
|
||||
|
|
@ -1,8 +1,22 @@
|
|||
//! The 'mach' CLI and engine editor
|
||||
|
||||
// Check that the user's app matches the required interface.
|
||||
comptime {
|
||||
if (!@import("builtin").is_test) @import("core").AppInterface(@import("app"));
|
||||
}
|
||||
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const App = @import("app").App;
|
||||
const core = @import("core");
|
||||
const gpu = core.gpu;
|
||||
|
||||
const Builder = @import("Builder.zig");
|
||||
const Target = @import("target.zig").Target;
|
||||
|
||||
pub const GPUInterface = gpu.dawn.Interface;
|
||||
|
||||
const default_zig_path = "zig";
|
||||
|
||||
var args: []const [:0]u8 = undefined;
|
||||
|
|
@ -10,13 +24,24 @@ var arg_i: usize = 1;
|
|||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
pub const allocator = gpa.allocator();
|
||||
|
||||
pub fn Main() !void {
|
||||
pub fn main() !void {
|
||||
defer _ = gpa.deinit();
|
||||
|
||||
args = try std.process.argsAlloc(allocator);
|
||||
defer std.process.argsFree(allocator, args);
|
||||
|
||||
if (args.len == 1) return;
|
||||
if (args.len == 1) {
|
||||
gpu.Impl.init();
|
||||
_ = gpu.Export(GPUInterface);
|
||||
|
||||
var app: App = undefined;
|
||||
try app.init();
|
||||
defer app.deinit();
|
||||
|
||||
while (true) {
|
||||
if (try app.update()) return;
|
||||
}
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, args[arg_i], "build")) {
|
||||
arg_i += 1;
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
const std = @import("std");
|
||||
const allocator = @import("entrypoint.zig").allocator;
|
||||
const allocator = @import("main.zig").allocator;
|
||||
|
||||
pub const Target = enum {
|
||||
@"linux-x86_64",
|
||||
|
|
|
|||
23
src/editor/vert.wgsl
Executable file
23
src/editor/vert.wgsl
Executable file
|
|
@ -0,0 +1,23 @@
|
|||
struct VertexOut {
|
||||
@builtin(position) position_clip : vec4<f32>,
|
||||
@location(0) frag_uv : vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex fn main(@builtin(vertex_index) index : u32) -> VertexOut {
|
||||
var pos = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
);
|
||||
|
||||
var uv = array<vec2<f32>, 3>(
|
||||
vec2<f32>(0.0, 0.0),
|
||||
vec2<f32>(2.0, 0.0),
|
||||
vec2<f32>(0.0, 2.0),
|
||||
);
|
||||
|
||||
var output : VertexOut;
|
||||
output.position_clip = vec4<f32>(pos[index], 0.0, 1.0);
|
||||
output.frag_uv = uv[index];
|
||||
return output;
|
||||
}
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
//! The 'mach' CLI and engine editor
|
||||
|
||||
const entrypoint = @import("editor/entrypoint.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
try entrypoint.Main();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue