diff --git a/engine/build.zig b/engine/build.zig index 21fc4d4..699b32e 100644 --- a/engine/build.zig +++ b/engine/build.zig @@ -14,7 +14,8 @@ pub fn build(b: *std.Build) void { }); const parse_interface_core = b.addRunArtifact(parser); - parse_interface_core.addArgs(&.{ "--input", b.path("src/core/core.zig").getPath(b) }); + parse_interface_core.addArgs(&.{"--input"}); + parse_interface_core.addFileInput(b.path("core/src/core.zig")); const generate_headers_step = b.step("generate-interface", "generates interface information from all core apis"); diff --git a/engine/lib/bh/build.zig b/engine/lib/bh/build.zig new file mode 100644 index 0000000..730621f --- /dev/null +++ b/engine/lib/bh/build.zig @@ -0,0 +1,155 @@ +const std = @import("std"); + +pub const ModLib = struct { + b: *std.Build, + lib: *std.Build.Step.Compile, + mod: *std.Build.Module, + + pub fn install(self: @This()) void { + self.b.installArtifact(self.lib); + } +}; + +pub const ModLibOptions = struct { + name: []const u8, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + monolithic: bool, + allow_dynamic: bool = false, + link_libc: bool = false, + link_libcpp: bool = false, + root: ?std.Build.LazyPath = null, + stub: ?std.Build.LazyPath = null, +}; + +pub fn MakeModlib(b: *std.Build, o: ModLibOptions) ModLib { + const mod = b.addModule(o.name, .{ + .target = o.target, + .optimize = o.optimize, + .root_source_file = if (o.root != null) o.root.? else b.path(b.fmt("src/{s}", .{o.name})), + }); + + const empty_file = b.addWriteFile("stubs", ""); + + const lib = b.addLibrary(.{ + .name = o.name, + .linkage = if (o.allow_dynamic and !o.monolithic) .dynamic else .static, + .root_module = b.createModule(.{ + .root_source_file = empty_file.add("stubc.zig", ""), + .target = o.target, + .optimize = o.optimize, + }), + }); + + return .{ + .b = b, + .lib = lib, + .mod = mod, + }; +} + +pub const Options = struct { + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + monolithic: bool, + tracy: bool, + renderer: []const u8, + box3d_validate: ?bool = null, +}; + +// standard set of options that all RibTech modules and dependenices shall use. +pub fn declareOptions(b: *std.Build) Options { + return .{ + .target = b.standardTargetOptions(.{}), + .optimize = b.standardOptimizeOption(.{}), + .monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false, + .tracy = b.option(bool, "tracy", "builds with tracy support") orelse false, + .renderer = b.option([]const u8, "renderer", "renderer backend: sgpu_main, gl_low_spec, headless") orelse "sgpu_main", + .box3d_validate = b.option(bool, "box3d-validate", "enable heavy Box3D validation"), + }; +} + +pub fn dependency(b: *std.Build, name: []const u8, opts: Options) *std.Build.Dependency { + if (std.mem.eql(u8, name, "physics")) { + return b.dependency(name, .{ + .target = opts.target, + .optimize = opts.optimize, + .monolithic = opts.monolithic, + .tracy = opts.tracy, + .renderer = opts.renderer, + .@"box3d-validate" = opts.box3d_validate, + }); + } + + if (isEngineDependency(name)) { + return b.dependency(name, .{ + .target = opts.target, + .optimize = opts.optimize, + .monolithic = opts.monolithic, + .tracy = opts.tracy, + .renderer = opts.renderer, + }); + } + + return b.dependency(name, .{ + .target = opts.target, + .optimize = opts.optimize, + .monolithic = opts.monolithic, + .tracy = opts.tracy, + }); +} + +pub fn isEngineDependency(name: []const u8) bool { + const engine_deps = [_][]const u8{ + "assets", + "audio", + "cook", + "core", + "desktopKit", + "devkit", + "editorkit", + "net", + "netgame", + "nav", + "bsp", + "papyrus", + "platform", + "rend", + "ui", + "physics", + "sys", + }; + + for (engine_deps) |dep_name| { + if (std.mem.eql(u8, dep_name, name)) return true; + } + return false; +} + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false; + + const r = MakeModlib(b, .{ + .name = "bh", + .target = target, + .optimize = optimize, + .monolithic = monolithic, + }); + + b.installArtifact(r.lib); + + const test_step = b.step("test", "run unit tests for enet"); + const tests = b.addTest(.{ + .root_module = b.createModule(.{ + .link_libc = true, + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/tests.zig"), + }), + }); + + const runArtifact = b.addRunArtifact(tests); + test_step.dependOn(&runArtifact.step); +} diff --git a/engine/lib/bh/build.zig.zon b/engine/lib/bh/build.zig.zon new file mode 100644 index 0000000..c47162d --- /dev/null +++ b/engine/lib/bh/build.zig.zon @@ -0,0 +1,10 @@ +.{ + .name = .bh, + .version = "0.0.0", + .dependencies = .{ + }, + .paths = .{ + "", + }, + .fingerprint = 0x557bf2b094ba1492, +} diff --git a/engine/lib/bh/src/bh.zig b/engine/lib/bh/src/bh.zig new file mode 100644 index 0000000..e69de29 diff --git a/engine/lib/bh/src/tests.zig b/engine/lib/bh/src/tests.zig new file mode 100644 index 0000000..e69de29 diff --git a/engine/lib/bh/stubc.zig b/engine/lib/bh/stubc.zig new file mode 100644 index 0000000..e69de29 diff --git a/engine/p2/.gitignore b/engine/lib/p2/.gitignore similarity index 100% rename from engine/p2/.gitignore rename to engine/lib/p2/.gitignore diff --git a/engine/p2/LICENSE b/engine/lib/p2/LICENSE similarity index 100% rename from engine/p2/LICENSE rename to engine/lib/p2/LICENSE diff --git a/engine/p2/Readme.md b/engine/lib/p2/Readme.md similarity index 100% rename from engine/p2/Readme.md rename to engine/lib/p2/Readme.md diff --git a/engine/p2/build.zig b/engine/lib/p2/build.zig similarity index 93% rename from engine/p2/build.zig rename to engine/lib/p2/build.zig index 69a6dab..13c2623 100644 --- a/engine/p2/build.zig +++ b/engine/lib/p2/build.zig @@ -28,9 +28,7 @@ pub fn build(b: *std.Build) void { const runArtifact = b.addRunArtifact(tests); test_step.dependOn(&installArtifact.step); test_step.dependOn(&runArtifact.step); - if (b.args) |args| { - runArtifact.addArgs(args); - } + runArtifact.addPassthruArgs(); b.installArtifact(tests); const benchmark = b.addExecutable(.{ @@ -42,6 +40,6 @@ pub fn build(b: *std.Build) void { }), }); const runBenchmark = b.addRunArtifact(benchmark); - if (b.args) |args| runBenchmark.addArgs(args); + runBenchmark.addPassthruArgs(); b.step("bench-queues", "Compare one-producer/many-consumer queue throughput").dependOn(&runBenchmark.step); } diff --git a/engine/p2/build.zig.zon b/engine/lib/p2/build.zig.zon similarity index 100% rename from engine/p2/build.zig.zon rename to engine/lib/p2/build.zig.zon diff --git a/engine/p2/debugging/lldb_std_formatters.py b/engine/lib/p2/debugging/lldb_std_formatters.py similarity index 100% rename from engine/p2/debugging/lldb_std_formatters.py rename to engine/lib/p2/debugging/lldb_std_formatters.py diff --git a/engine/p2/src/algorithm/pointer-hash.zig b/engine/lib/p2/src/algorithm/pointer-hash.zig similarity index 100% rename from engine/p2/src/algorithm/pointer-hash.zig rename to engine/lib/p2/src/algorithm/pointer-hash.zig diff --git a/engine/p2/src/p2.zig b/engine/lib/p2/src/p2.zig similarity index 99% rename from engine/p2/src/p2.zig rename to engine/lib/p2/src/p2.zig index d667d4b..eeb7dfa 100644 --- a/engine/p2/src/p2.zig +++ b/engine/lib/p2/src/p2.zig @@ -3,6 +3,9 @@ const std = @import("std"); pub const stats = @import("structures/stats.zig"); pub const PoolStatistics = stats.PoolStatistics; +pub const structured_logging = @import("structures/structured-logging.zig"); +pub const + const utils = @import("structures/utils.zig"); pub const getFileExtension = utils.getFileExtension; diff --git a/engine/p2/src/queue-benchmark-cas-baseline.zig b/engine/lib/p2/src/queue-benchmark-cas-baseline.zig similarity index 100% rename from engine/p2/src/queue-benchmark-cas-baseline.zig rename to engine/lib/p2/src/queue-benchmark-cas-baseline.zig diff --git a/engine/p2/src/queue-benchmark.zig b/engine/lib/p2/src/queue-benchmark.zig similarity index 100% rename from engine/p2/src/queue-benchmark.zig rename to engine/lib/p2/src/queue-benchmark.zig diff --git a/engine/p2/src/structures/bump-arena.zig b/engine/lib/p2/src/structures/bump-arena.zig similarity index 100% rename from engine/p2/src/structures/bump-arena.zig rename to engine/lib/p2/src/structures/bump-arena.zig diff --git a/engine/p2/src/structures/concurrent-queue.zig b/engine/lib/p2/src/structures/concurrent-queue.zig similarity index 100% rename from engine/p2/src/structures/concurrent-queue.zig rename to engine/lib/p2/src/structures/concurrent-queue.zig diff --git a/engine/p2/src/structures/counting-allocator.zig b/engine/lib/p2/src/structures/counting-allocator.zig similarity index 100% rename from engine/p2/src/structures/counting-allocator.zig rename to engine/lib/p2/src/structures/counting-allocator.zig diff --git a/engine/p2/src/structures/index-pool.zig b/engine/lib/p2/src/structures/index-pool.zig similarity index 100% rename from engine/p2/src/structures/index-pool.zig rename to engine/lib/p2/src/structures/index-pool.zig diff --git a/engine/p2/src/structures/int-mapper.zig b/engine/lib/p2/src/structures/int-mapper.zig similarity index 100% rename from engine/p2/src/structures/int-mapper.zig rename to engine/lib/p2/src/structures/int-mapper.zig diff --git a/engine/p2/src/structures/interface.zig b/engine/lib/p2/src/structures/interface.zig similarity index 100% rename from engine/p2/src/structures/interface.zig rename to engine/lib/p2/src/structures/interface.zig diff --git a/engine/p2/src/structures/math.zig b/engine/lib/p2/src/structures/math.zig similarity index 100% rename from engine/p2/src/structures/math.zig rename to engine/lib/p2/src/structures/math.zig diff --git a/engine/p2/src/structures/names.zig b/engine/lib/p2/src/structures/names.zig similarity index 100% rename from engine/p2/src/structures/names.zig rename to engine/lib/p2/src/structures/names.zig diff --git a/engine/p2/src/structures/paged-vector.zig b/engine/lib/p2/src/structures/paged-vector.zig similarity index 100% rename from engine/p2/src/structures/paged-vector.zig rename to engine/lib/p2/src/structures/paged-vector.zig diff --git a/engine/p2/src/structures/perf-tests.zig b/engine/lib/p2/src/structures/perf-tests.zig similarity index 100% rename from engine/p2/src/structures/perf-tests.zig rename to engine/lib/p2/src/structures/perf-tests.zig diff --git a/engine/p2/src/structures/pscopes.zig b/engine/lib/p2/src/structures/pscopes.zig similarity index 100% rename from engine/p2/src/structures/pscopes.zig rename to engine/lib/p2/src/structures/pscopes.zig diff --git a/engine/p2/src/structures/ref-pool.zig b/engine/lib/p2/src/structures/ref-pool.zig similarity index 100% rename from engine/p2/src/structures/ref-pool.zig rename to engine/lib/p2/src/structures/ref-pool.zig diff --git a/engine/p2/src/structures/ref-string-map.zig b/engine/lib/p2/src/structures/ref-string-map.zig similarity index 100% rename from engine/p2/src/structures/ref-string-map.zig rename to engine/lib/p2/src/structures/ref-string-map.zig diff --git a/engine/p2/src/structures/ring-queue.zig b/engine/lib/p2/src/structures/ring-queue.zig similarity index 100% rename from engine/p2/src/structures/ring-queue.zig rename to engine/lib/p2/src/structures/ring-queue.zig diff --git a/engine/p2/src/structures/samplegun.json b/engine/lib/p2/src/structures/samplegun.json similarity index 100% rename from engine/p2/src/structures/samplegun.json rename to engine/lib/p2/src/structures/samplegun.json diff --git a/engine/p2/src/structures/spans.zig b/engine/lib/p2/src/structures/spans.zig similarity index 100% rename from engine/p2/src/structures/spans.zig rename to engine/lib/p2/src/structures/spans.zig diff --git a/engine/p2/src/structures/sparse-set.zig b/engine/lib/p2/src/structures/sparse-set.zig similarity index 100% rename from engine/p2/src/structures/sparse-set.zig rename to engine/lib/p2/src/structures/sparse-set.zig diff --git a/engine/p2/src/structures/spmc-submission-queue.zig b/engine/lib/p2/src/structures/spmc-submission-queue.zig similarity index 100% rename from engine/p2/src/structures/spmc-submission-queue.zig rename to engine/lib/p2/src/structures/spmc-submission-queue.zig diff --git a/engine/p2/src/structures/static-structures.zig b/engine/lib/p2/src/structures/static-structures.zig similarity index 100% rename from engine/p2/src/structures/static-structures.zig rename to engine/lib/p2/src/structures/static-structures.zig diff --git a/engine/p2/src/structures/stats.zig b/engine/lib/p2/src/structures/stats.zig similarity index 100% rename from engine/p2/src/structures/stats.zig rename to engine/lib/p2/src/structures/stats.zig diff --git a/engine/p2/src/structures/string-pool.zig b/engine/lib/p2/src/structures/string-pool.zig similarity index 100% rename from engine/p2/src/structures/string-pool.zig rename to engine/lib/p2/src/structures/string-pool.zig diff --git a/engine/lib/p2/src/structures/structured-logging.zig b/engine/lib/p2/src/structures/structured-logging.zig new file mode 100644 index 0000000..abc25a9 --- /dev/null +++ b/engine/lib/p2/src/structures/structured-logging.zig @@ -0,0 +1,343 @@ +// experiment with a specialized logging infrastructure. +// structured logging. +// +// It can log to an ultra tiny in-memory buffer directly, +// or it can log to a second writer thread. +// but the way it all works is it goes through this logger + +const BumpArena = @import("bump-arena.zig"); + +pub const ArgsSerializerOpKind = enum { + integer, + floating, + string, // []u8 and []const u8 + structure, +}; + +pub const ArgsSerializerOp = struct { + kind: ArgsSerializerOpKind, +}; + +pub const ArgsSerializer = struct { + ops: []const ArgsSerializerOp, + + pub const Error = std.Io.Writer.Error || error{ + InvalidOperationCount, + InvalidOperation, + IntegerOutOfRange, + StringTooLong, + }; + + /// Numbers use little endian. Comptime integers use u32 and comptime floats + /// use f64. Typed numbers retain their width, rounded up to whole bytes. + /// Strings have a u32 byte length followed by their contents. Struct fields + /// are encoded recursively in declaration order, without padding or tags. + /// The decoder must know the argument types and struct field schema. + pub fn serialize(self: @This(), args: anytype, output: *std.Io.Writer) Error!void { + if (self.ops.len != args.len) return error.InvalidOperationCount; + // Validate the entire op list before writing any arguments. + inline for (args, 0..) |a, i| { + if (self.ops[i].kind != kindFor(@TypeOf(a))) return error.InvalidOperation; + } + inline for (args) |a| { + try writeValue(a, output); + } + } + + fn kindFor(comptime T: type) ArgsSerializerOpKind { + return switch (@typeInfo(T)) { + .comptime_int, .int => .integer, + .comptime_float, .float => .floating, + .@"struct" => .structure, + .pointer => |ptr| blk: { + if (ptr.size == .slice and ptr.child == u8) break :blk .string; + if (ptr.size == .one) { + switch (@typeInfo(ptr.child)) { + .array => |array| if (array.child == u8) break :blk .string, + else => {}, + } + } + @compileError("Unsupported serializer type: " ++ @typeName(T)); + }, + else => @compileError("Unsupported serializer type: " ++ @typeName(T)), + }; + } + + fn writeValue(value: anytype, output: *std.Io.Writer) Error!void { + const T = @TypeOf(value); + switch (comptime kindFor(T)) { + .integer => { + if (T == comptime_int) { + return output.writeInt(u32, std.math.cast(u32, value) orelse return error.IntegerOutOfRange, .little); + } + const int = @typeInfo(T).int; + const Encoded = @Int(int.signedness, ((int.bits + 7) / 8) * 8); + try output.writeInt(Encoded, value, .little); + }, + .floating => { + if (T == comptime_float) return writeValue(@as(f64, value), output); + const Bits = @Int(.unsigned, @bitSizeOf(T)); + try writeValue(@as(Bits, @bitCast(value)), output); + }, + .string => { + const bytes: []const u8 = value; + const len = std.math.cast(u32, bytes.len) orelse return error.StringTooLong; + try output.writeInt(u32, len, .little); + try output.writeAll(bytes); + }, + .structure => { + inline for (@typeInfo(T).@"struct".field_names) |field_name| { + try writeValue(@field(value, field_name), output); + } + }, + } + } +}; + +pub const Verbosity = enum(u8) { + verbose, + log, + warn, + err, +}; + +test "argsSerializer tests" { + const expectBytes = struct { + fn check(ops: []const ArgsSerializerOp, args: anytype, expected: []const u8) !void { + var writer = std.Io.Writer.Allocating.init(std.testing.allocator); + defer writer.deinit(); + try (ArgsSerializer{ .ops = ops }).serialize(args, &writer.writer); + try std.testing.expectEqualSlices(u8, expected, writer.written()); + } + }.check; + + // Existing comptime integer representation, including its upper boundary. + try expectBytes(&.{ + .{ .kind = .integer }, .{ .kind = .integer }, + .{ .kind = .integer }, .{ .kind = .integer }, + }, .{ 0, 2, 3, 0xffffffff }, &.{ + 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 255, 255, 255, 255, + }); + try expectBytes(&.{.{ .kind = .floating }}, .{1.5}, &.{ 0, 0, 0, 0, 0, 0, 0xf8, 0x3f }); + + // Runtime values, signed integers, and widths that need byte rounding. + var number: i16 = -2; + _ = &number; + try expectBytes(&.{ + .{ .kind = .integer }, .{ .kind = .integer }, .{ .kind = .integer }, + .{ .kind = .integer }, .{ .kind = .integer }, .{ .kind = .integer }, + }, .{ number, @as(u8, 255), @as(u32, 0x12345678), @as(u64, 0x0102030405060708), @as(u12, 0xabc), @as(i7, -1) }, &.{ + 0xfe, 0xff, 0xff, 0x78, 0x56, 0x34, 0x12, + 8, 7, 6, 5, 4, 3, 2, + 1, 0xbc, 0x0a, 0xff, + }); + try expectBytes(&.{ .{ .kind = .floating }, .{ .kind = .floating }, .{ .kind = .floating } }, .{ @as(f16, 1.0), @as(f32, -2.5), @as(f64, -0.0) }, &.{ 0, 0x3c, 0, 0, 0x20, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0x80 }); + + var mutable = [_]u8{ 'a', 0, 'b' }; + const immutable: []const u8 = "hi"; + try expectBytes(&.{ + .{ .kind = .string }, .{ .kind = .string }, .{ .kind = .string }, .{ .kind = .string }, + }, .{ mutable[0..], immutable, "", "Z" }, &.{ + 3, 0, 0, 0, 'a', 0, 'b', 2, 0, 0, 0, 'h', 'i', 0, 0, 0, 0, 1, 0, 0, 0, 'Z', + }); + // Explicitly exercise a mutable slice, not just a pointer to an array. + const mutable_slice: []u8 = &mutable; + try expectBytes(&.{.{ .kind = .string }}, .{mutable_slice}, &.{ 3, 0, 0, 0, 'a', 0, 'b' }); + + const Record = struct { + tag: u8, + count: u32, + nested: struct { amount: f32, label: []const u8 }, + }; + try expectBytes(&.{ .{ .kind = .structure }, .{ .kind = .integer } }, .{ + Record{ .tag = 7, .count = 0x12345678, .nested = .{ .amount = 1.0, .label = "ok" } }, @as(u8, 9), + }, &.{ 7, 0x78, 0x56, 0x34, 0x12, 0, 0, 0x80, 0x3f, 2, 0, 0, 0, 'o', 'k', 9 }); + try expectBytes(&.{.{ .kind = .structure }}, .{struct {}{}}, &.{}); + try expectBytes(&.{}, .{}, &.{}); + + var writer = std.Io.Writer.Allocating.init(std.testing.allocator); + defer writer.deinit(); + const integers = ArgsSerializer{ .ops = &.{.{ .kind = .integer }} }; + try std.testing.expectError(error.IntegerOutOfRange, integers.serialize(.{-1}, &writer.writer)); + try std.testing.expectError(error.IntegerOutOfRange, integers.serialize(.{0x100000000}, &writer.writer)); + try std.testing.expectError(error.InvalidOperationCount, integers.serialize(.{}, &writer.writer)); + try std.testing.expectError(error.InvalidOperationCount, integers.serialize(.{ 1, 2 }, &writer.writer)); + const mismatched = ArgsSerializer{ .ops = &.{ .{ .kind = .integer }, .{ .kind = .floating } } }; + try std.testing.expectError(error.InvalidOperation, mismatched.serialize(.{ 1, @as(u8, 2) }, &writer.writer)); + try std.testing.expectEqual(@as(usize, 0), writer.written().len); + + // A partial/failed write must propagate instead of silently losing bytes. + var small_buffer: [2]u8 = undefined; + var limited = std.Io.Writer.fixed(&small_buffer); + try std.testing.expectError(error.WriteFailed, integers.serialize(.{1}, &limited)); +} + +var gLoggerContext: LoggerContext = undefined; + +pub const LoggerContext = struct { + stdout_buffer: [8192 * 8]u8 = undefined, + stdout_file_writer: std.Io.File.Writer = undefined, + stdout_writer: *std.Io.Writer = undefined, + + arena: std.heap.ArenaAllocator = undefined, + backing: std.mem.Allocator = undefined, + + logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty, + logMapById: std.ArrayList(LogRef) = .empty, + + loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, + loggerStatesById: std.ArrayList(*LoggerState) = .empty, + + // keyed by id (u32 index) + serializers: std.ArrayList(ArgsSerializer) = .empty, + + pub fn insertLoggerStateOrGetId(self: *@This(), state: *LoggerState) u32 { + if (state.id > -1) { + return @intCast(state.id); + } + + if (self.loggerStates.get(state)) |id| { + return id; + } + const allocator = self.arena.allocator(); + + const rv: u32 = @intCast(self.loggerStatesById.items.len); + self.loggerStates.put(allocator, state, rv) catch @panic("unbounded arena oom"); + self.loggerStatesById.append(allocator, state) catch @panic("unbounded arena saw oom"); + return rv; + } + + pub fn insertLogRefOrGetId(self: *@This(), ref: LogRef, idref: *i32) u32 { + if (idref.* > -1) { + return @intCast(idref.*); + } + + if (self.logMap.get(ref)) |key| { + idref.* = @intCast(key); + return key; + } + + const allocator = self.arena.allocator(); + const rv: u32 = @intCast(self.logMapById.items.len); + self.logMapById.append(allocator, ref) catch @panic("unbounded arena saw oom"); + self.logMap.put(allocator, ref, rv) catch @panic("unbounded arena saw oom"); + idref.* = @intCast(rv); + + return rv; + } + + pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void { + self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer); + self.stdout_writer = &self.stdout_file_writer.interface; + + self.backing = allocator; + self.arena = std.heap.ArenaAllocator.init(self.backing); + } + + pub fn deinit(self: *@This()) void { + self.arena.deinit(); + } +}; + +pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void { + gLoggerContext.init(io, allocator); +} + +pub fn deinit() void { + gLoggerContext.deinit(); +} +pub fn flush() void { + gLoggerContext.stdout_writer.flush() catch {}; +} + +pub const LogRef = struct { + line: u32, + file: []const u8, + fmt: []const u8, + + pub const Context = struct { + pub fn hash(_: @This(), key: LogRef) u64 { + var hasher = std.hash.Wyhash.init(0); + hasher.update(key.file); + hasher.update(std.mem.asBytes(&key.line)); + hasher.update(std.mem.asBytes(&key.fmt)); + return hasher.final(); + } + + pub fn eql(_: @This(), a: LogRef, b: LogRef) bool { + return a.line == b.line and std.mem.eql(u8, a.file, b.file); + } + }; + + pub fn fromSrcFmt(comptime s: std.builtin.SourceLocation, comptime fmt: []const u8) @This() { + return .{ + .line = s.line, + .file = @ptrCast(s.file), + .fmt = fmt, + }; + } +}; + +pub const LoggerState = struct { + name: []const u8, + verbosity: Verbosity, + id: i32 = -1, + stdout: bool = false, // mirrors it's output to stdout +}; + +pub const LoggerOptions = struct { + verbosity: Verbosity = .verbose, + has_stdout: bool = false, +}; + +pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptions) type { + return struct { + pub var loggerState: LoggerState = .{ + .name = LoggerName, + .verbosity = opts.verbosity, + }; + + pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void { + const FmtState = struct { + pub const FMT = fmt; + pub const source = s; + pub var index: i32 = -1; + }; + + // create a hash of the s: builtin sourcelocation + const sourceId = gLoggerContext.insertLogRefOrGetId(LogRef.fromSrcFmt(s, fmt), &FmtState.index); + const loggerId = gLoggerContext.insertLoggerStateOrGetId(&loggerState); + + if (@backingInt(loggerState.verbosity) > @backingInt(v)) { + return; + } + + const debug = true; + if (debug) { + gLoggerContext.stdout_writer.print("[{d}] [{d}] ", .{ loggerId, sourceId }) catch @panic("io error"); + gLoggerContext.stdout_writer.print(fmt ++ "\n", args) catch @panic("io error"); + gLoggerContext.stdout_writer.flush() catch @panic("debug io error"); + } + + // stash the logs into the logger's in-memory log + // const serialized_args = gLoggerContext.serializeLogEntryArgs(sourceId, args); + // gLoggerContext.submit(loggerId, sourceId, serialized_args); + } + }; +} + +const std = @import("std"); +const builtin = @import("builtin"); + +test "init logger" { + initialize(std.testing.io, std.testing.allocator); + defer deinit(); + + const TestLogger = DeclareLogger("Testing", .{}); + TestLogger.addLog(@src(), .log, "testing", .{}); + TestLogger.addLog(@src(), .log, "testing", .{}); + TestLogger.addLog(@src(), .log, "testing", .{}); + TestLogger.addLog(@src(), .log, "testing", .{}); + + flush(); +} diff --git a/engine/p2/src/structures/utils.zig b/engine/lib/p2/src/structures/utils.zig similarity index 100% rename from engine/p2/src/structures/utils.zig rename to engine/lib/p2/src/structures/utils.zig diff --git a/engine/p2/src/structures/zmath.zig b/engine/lib/p2/src/structures/zmath.zig similarity index 100% rename from engine/p2/src/structures/zmath.zig rename to engine/lib/p2/src/structures/zmath.zig diff --git a/engine/p2/src/utils/shell.zig b/engine/lib/p2/src/utils/shell.zig similarity index 100% rename from engine/p2/src/utils/shell.zig rename to engine/lib/p2/src/utils/shell.zig diff --git a/engine/p2/src/utils/xxd.zig b/engine/lib/p2/src/utils/xxd.zig similarity index 100% rename from engine/p2/src/utils/xxd.zig rename to engine/lib/p2/src/utils/xxd.zig diff --git a/engine/p2/tools/vscode-env/README.md b/engine/lib/p2/tools/vscode-env/README.md similarity index 100% rename from engine/p2/tools/vscode-env/README.md rename to engine/lib/p2/tools/vscode-env/README.md diff --git a/engine/p2/tools/vscode-env/extensions/.gitkeep b/engine/lib/p2/tools/vscode-env/extensions/.gitkeep similarity index 100% rename from engine/p2/tools/vscode-env/extensions/.gitkeep rename to engine/lib/p2/tools/vscode-env/extensions/.gitkeep diff --git a/engine/p2/tools/vscode-env/install.bat b/engine/lib/p2/tools/vscode-env/install.bat similarity index 100% rename from engine/p2/tools/vscode-env/install.bat rename to engine/lib/p2/tools/vscode-env/install.bat diff --git a/engine/p2/tools/vscode-env/install.sh b/engine/lib/p2/tools/vscode-env/install.sh similarity index 100% rename from engine/p2/tools/vscode-env/install.sh rename to engine/lib/p2/tools/vscode-env/install.sh diff --git a/engine/p2/tools/vscode-env/settings/settings.json b/engine/lib/p2/tools/vscode-env/settings/settings.json similarity index 100% rename from engine/p2/tools/vscode-env/settings/settings.json rename to engine/lib/p2/tools/vscode-env/settings/settings.json diff --git a/engine/p2/src/structures/structured-logging.zig b/engine/p2/src/structures/structured-logging.zig deleted file mode 100644 index a33258d..0000000 --- a/engine/p2/src/structures/structured-logging.zig +++ /dev/null @@ -1,164 +0,0 @@ -// experiment with a specialized logging infrastructure. -// structured logging. -// -// It can log to an ultra tiny in-memory buffer directly, -// or it can log to a second writer thread. -// but the way it all works is it goes through this logger - -const BumpArena = @import("bump-arena.zig"); - -pub const Verbosity = enum(u8) { - verbose, - log, - warn, - err, -}; - -var gLoggerContext: LoggerContext = undefined; - -pub const LoggerContext = struct { - stdout_buffer: [8192 * 8]u8 = undefined, - stdout_file_writer: std.Io.File.Writer = undefined, - stdout_writer: *std.Io.Writer = undefined, - - arena: std.heap.ArenaAllocator = undefined, - backing: std.mem.Allocator = undefined, - - logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty, - logMapById: std.ArrayList(LogRef) = .empty, - - loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, - loggerStatesById: std.ArrayList(*LoggerState) = .empty, - - pub fn insertLoggerStateOrGetId(self: *@This(), state: *LoggerState) u32 { - if (state.id > -1) { - return @intCast(state.id); - } - - if (self.loggerStates.get(state)) |id| { - return id; - } - const allocator = self.arena.allocator(); - - const rv: u32 = @intCast(self.loggerStatesById.items.len); - self.loggerStates.put(allocator, state, rv) catch @panic("unbounded arena oom"); - self.loggerStatesById.append(allocator, state) catch @panic("unbounded arena saw oom"); - return rv; - } - - pub fn insertLogRefOrGetId(self: *@This(), ref: LogRef, idref: *i32) u32 { - if (idref.* > -1) { - return @intCast(idref.*); - } - - if (self.logMap.get(ref)) |key| { - idref.* = @intCast(key); - return key; - } - - const allocator = self.arena.allocator(); - const rv: u32 = @intCast(self.logMapById.items.len); - self.logMapById.append(allocator, ref) catch @panic("unbounded arena saw oom"); - self.logMap.put(allocator, ref, rv) catch @panic("unbounded arena saw oom"); - idref.* = @intCast(rv); - - return rv; - } - - pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void { - self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer); - self.stdout_writer = &self.stdout_file_writer.interface; - - self.backing = allocator; - self.arena = std.heap.ArenaAllocator.init(self.backing); - } - - pub fn deinit(self: *@This()) void { - self.arena.deinit(); - } -}; - -pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void { - gLoggerContext.init(io, allocator); -} - -pub fn deinit() void { - gLoggerContext.deinit(); -} -pub fn flush() void { - gLoggerContext.stdout_writer.flush() catch {}; -} - -pub const LogRef = struct { - line: u32, - file: []const u8, - fmt: []const u8, - - pub const Context = struct { - pub fn hash(_: @This(), key: LogRef) u64 { - var hasher = std.hash.Wyhash.init(0); - hasher.update(key.file); - hasher.update(std.mem.asBytes(&key.line)); - hasher.update(std.mem.asBytes(&key.fmt)); - return hasher.final(); - } - - pub fn eql(_: @This(), a: LogRef, b: LogRef) bool { - return a.line == b.line and std.mem.eql(u8, a.file, b.file); - } - }; - - pub fn fromSrcFmt(comptime s: std.builtin.SourceLocation, comptime fmt: []const u8) @This() { - return .{ - .line = s.line, - .file = @ptrCast(s.file), - .fmt = fmt, - }; - } -}; - -pub const LoggerState = struct { name: []const u8, verbosity: Verbosity, id: i32 = -1 }; - -pub fn DeclareLogger(comptime LoggerName: []const u8, defaultVerbosity: Verbosity) type { - return struct { - pub var loggerState: LoggerState = .{ - .name = LoggerName, - .verbosity = defaultVerbosity, - }; - - const debug = true; - - pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void { - const FmtState = struct { - pub const FMT = fmt; - pub var index: i32 = -1; - }; - - // create a hash of the s: builtin sourcelocation - const sourceId = gLoggerContext.insertLogRefOrGetId(LogRef.fromSrcFmt(s, fmt), &FmtState.index); - const loggerId = gLoggerContext.insertLoggerStateOrGetId(&loggerState); - - if (@intFromEnum(loggerState.verbosity) > @intFromEnum(v)) { - return; - } - - if (debug) { - gLoggerContext.stdout_writer.print("[{d}] [{d}] ", .{ loggerId, sourceId }) catch @panic("io error"); - gLoggerContext.stdout_writer.print(fmt ++ "\n", args) catch @panic("io error"); - } - } - }; -} - -const std = @import("std"); -const builtin = @import("builtin"); - -test "init logger" { - initialize(std.testing.io, std.testing.allocator); - defer deinit(); - - const TestLogger = DeclareLogger("Testing", .log); - TestLogger.addLog(@src(), .log, "testing", .{}); - - flush(); -} diff --git a/engine/src/core/core.zig b/engine/src/core/core.zig index e2e74ce..22b0fdf 100644 --- a/engine/src/core/core.zig +++ b/engine/src/core/core.zig @@ -1,4 +1,16 @@ -/// desc: we will we will rock you +/// desc: publically exported C slice +pub const RtSlice = extern struct { + ptr: [*c]u8, + len: usize, + + pub fn fromZ(s: []const u8) @This() { + return .{ .ptr = s.ptr, .len = s.len }; + } +}; + +/// desc: initializes the core module, pub export fn core_start() callconv(.c) void {} +pub export fn core_log(string: [*c]u8) callconv(.c) void {} + pub export fn core_shutdown() callconv(.c) void {} diff --git a/engine/tools/interface-parser.zig b/engine/tools/interface-parser.zig index 1bef439..a817c24 100644 --- a/engine/tools/interface-parser.zig +++ b/engine/tools/interface-parser.zig @@ -1,9 +1,9 @@ -// this thing eats a ribtech top level +// this thing eats a ribtech top level zig file and generates a C header pub fn main(init: std.process.Init) !void { const args = init.minimal.args; const argsSlice = try args.toSlice(init.arena.allocator()); - + const io = init.io; } const std = @import("std");