From 31141ebfb7a41fb58eb459ec4734d21f3e42e956 Mon Sep 17 00:00:00 2001 From: Hamcha Date: Mon, 6 May 2024 00:23:06 +0200 Subject: [PATCH] basic bdf parsing --- .gitignore | 5 ++ build.zig | 36 ++++++++++++ build.zig.zon | 67 ++++++++++++++++++++++ src/bdf.zig | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.zig | 29 ++++++++++ 5 files changed, 293 insertions(+) create mode 100644 .gitignore create mode 100644 build.zig create mode 100644 build.zig.zon create mode 100644 src/bdf.zig create mode 100644 src/main.zig diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c33c93b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +zig-cache +zig-out +*.bdf +out +*.font.zon \ No newline at end of file diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..b4db1f7 --- /dev/null +++ b/build.zig @@ -0,0 +1,36 @@ +const std = @import("std"); + +// Although this function looks imperative, note that its job is to +// declaratively construct a build graph that will be executed by an external +// runner. +pub fn build(b: *std.Build) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard optimization options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not + // set a preferred release mode, allowing the user to decide how to optimize. + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "binfon", + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + b.installArtifact(exe); + + const run_cmd = b.addRunArtifact(exe); + run_cmd.step.dependOn(b.getInstallStep()); + + if (b.args) |args| { + run_cmd.addArgs(args); + } + + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..b0d4140 --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,67 @@ +.{ + .name = "binfon", + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // This field is optional. + // This is currently advisory only; Zig does not yet do anything + // with this value. + //.minimum_zig_version = "0.11.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + // See `zig fetch --save ` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from a `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiformats.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + // This makes *all* files, recursively, included in this package. It is generally + // better to explicitly list the files and directories instead, to insure that + // fetching from tarballs, file system paths, and version control all result + // in the same contents hash. + "", + // For example... + //"build.zig", + //"build.zig.zon", + //"src", + //"LICENSE", + //"README.md", + }, +} diff --git a/src/bdf.zig b/src/bdf.zig new file mode 100644 index 0000000..2347499 --- /dev/null +++ b/src/bdf.zig @@ -0,0 +1,156 @@ +const std = @import("std"); + +const Bitmap = [][]u8; + +const Character = struct { + name: []u8, + bitmap: Bitmap, + + pub fn deinit(self: *Character, allocator: std.mem.Allocator) void { + for (self.bitmap) |line| { + allocator.free(line); + } + allocator.free(self.bitmap); + allocator.free(self.name); + } +}; +const CharacterMap = std.AutoHashMap(u16, Character); + +const Font = struct { + name: []const u8, + height: u8, + width: u8, + characters: CharacterMap, + + pub fn deinit(self: *Font, allocator: std.mem.Allocator) void { + var iterator = self.characters.valueIterator(); + while (iterator.next()) |char| { + char.deinit(allocator); + } + self.characters.deinit(); + } +}; + +const Command = enum { + FONT, + FONTBOUNDINGBOX, + ENCODING, + BITMAP, + STARTCHAR, + _IGNORED, +}; + +const Line = struct { + command: Command, + params: []const u8, +}; + +pub fn parse(allocator: std.mem.Allocator, bdf: anytype) !Font { + var font: Font = .{ + .name = undefined, + .height = 0, + .width = 0, + .characters = CharacterMap.init(allocator), + }; + + var bufferedReader = std.io.bufferedReader(bdf); + var reader = bufferedReader.reader(); + + var currentName: []const u8 = undefined; + var currentCharacter: u16 = 0; + while (true) { + var lineBuffer: [1024]u8 = undefined; + const nextLine = try reader.readUntilDelimiterOrEof(&lineBuffer, '\n') orelse break; + + // Parse line + const line = try parseLine(nextLine); + switch (line.command) { + .FONT => { + font.name = line.params; + std.log.debug("Font: {s}", .{font.name}); + }, + .FONTBOUNDINGBOX => { + var boundingBox = std.mem.splitScalar(u8, line.params, ' '); + font.width = try std.fmt.parseInt(u8, boundingBox.next().?, 10); + font.height = try std.fmt.parseInt(u8, boundingBox.next().?, 10); + + std.log.debug("Bounding box: {d}x{d}", .{ font.width, font.height }); + }, + .BITMAP => { + const bitmap = try readBitmap(allocator, font.width, font.height, reader); + try font.characters.put(currentCharacter, .{ + .name = try allocator.dupe(u8, currentName), + .bitmap = bitmap, + }); + }, + .STARTCHAR => { + currentName = line.params; + }, + .ENCODING => { + // This probably breaks with custom encodings, not doing anything for now + currentCharacter = try std.fmt.parseInt(u16, line.params, 10); + }, + else => {}, + } + } + + return font; +} + +fn parseLine(line: []const u8) !Line { + const firstSpace = std.mem.indexOfScalar(u8, line, ' ') orelse line.len; + const command = line[0..firstSpace]; + + return .{ + .command = std.meta.stringToEnum(Command, command) orelse Command._IGNORED, + .params = if (firstSpace == line.len) "" else line[firstSpace + 1 ..], + }; +} + +fn readBitmap( + allocator: std.mem.Allocator, + width: u8, + height: u8, + reader: anytype, +) !Bitmap { + var lineIndex: u8 = 0; + + var char = try allocator.alloc([]u8, height); + errdefer { + for (0..lineIndex) |i| { + allocator.free(char[i]); + } + allocator.free(char); + } + + // Allocate memory for the parsed bitmap + var line: []u8 = try allocator.alloc(u8, width / 8); + defer allocator.free(line); + + // Read lines until ENDCHAR + while (true) { + std.debug.assert(lineIndex < height + 1); + + // Read the next line + var lineBuffer: [128]u8 = undefined; + const nextLine = try reader.readUntilDelimiterOrEof(&lineBuffer, '\n') orelse break; + + // If we encounter the magic string, we're done + if (std.mem.eql(u8, nextLine, "ENDCHAR")) { + break; + } + + // Parse every 2 char as a hexadecimal number + var i: usize = 0; + while (i < nextLine.len) : (i += 2) { + const hex = try std.fmt.parseInt(u8, nextLine[i .. i + 2], 16); + line[i / 2] = hex; + } + + // Copy over to the array (this memory must be freed later) + char[lineIndex] = try allocator.dupe(u8, line); + lineIndex += 1; + } + + return char; +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..2210896 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,29 @@ +const std = @import("std"); +const bdf = @import("bdf.zig"); + +pub fn main() !void { + // Get allocator + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + // Get args + const args = try std.process.argsAlloc(allocator); + defer std.process.argsFree(allocator, args); + + if (args.len < 3) { + std.log.err("Usage: {s} ", .{args[0]}); + std.process.exit(1); + } + + const inputFile = args[1]; + const outputPath = args[2]; + _ = outputPath; // autofix + + // Read font + const input = try std.fs.cwd().openFile(inputFile, .{}); + defer input.close(); + + var font = try bdf.parse(allocator, input.reader()); + defer font.deinit(allocator); +}