aboutsummaryrefslogtreecommitdiff
path: root/zig-ppm/main.zig
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-09-15 11:06:58 +0200
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-09-15 11:06:58 +0200
commitf767af16befcd2ec346006461027508a19d4d4ee (patch)
treedbbfacf3a688cbbf79a6ae42f56009ae29c04a4e /zig-ppm/main.zig
parentd15e34b5a2ebe6fd7e61fbd53c40eaa712f44bd3 (diff)
downloadprobe-f767af16befcd2ec346006461027508a19d4d4ee.tar.gz
Added PPM image generation with Zig
Diffstat (limited to 'zig-ppm/main.zig')
-rw-r--r--zig-ppm/main.zig45
1 files changed, 45 insertions, 0 deletions
diff --git a/zig-ppm/main.zig b/zig-ppm/main.zig
new file mode 100644
index 0000000..4dc2439
--- /dev/null
+++ b/zig-ppm/main.zig
@@ -0,0 +1,45 @@
1// PPM image format - https://netpbm.sourceforge.net/doc/ppm.html
2
3const std = @import("std");
4const debug = @import("std").debug;
5
6const ImageSize = 600;
7
8const Color = struct {
9 r: u8,
10 g: u8,
11 b: u8,
12
13 pub fn initRandom() Color {
14 const rand = std.crypto.random;
15 return Color{
16 .r = rand.int(u8),
17 .g = rand.int(u8),
18 .b = rand.int(u8),
19 };
20 }
21
22 pub fn toString(self: Color) []const u8 {
23 return std.fmt.allocPrint(std.heap.page_allocator, "{d} {d} {d} ", .{ self.r, self.g, self.b }) catch unreachable;
24 }
25};
26
27pub fn main() !void {
28 const imageFile = try std.fs.cwd().createFile("image.ppm", .{});
29 defer imageFile.close();
30
31 // NOTE: This should be done at compile time instead since the data is
32 // known in advance. I am leaving this here as a reference.
33 // const header: []const u8 = std.fmt.allocPrint(std.heap.page_allocator, "P3\n{d} {d}\n255\n", .{ ImageSize, ImageSize }) catch unreachable;
34
35 // NOTE: This is done at compile time instead. It does look a bit ugly
36 // and there must be a better way of doing this. Good enough!
37 const header = "P3\n" ++ std.fmt.comptimePrint("{d}", .{ImageSize}) ++ " " ++ std.fmt.comptimePrint("{d}", .{ImageSize}) ++ "\n255\n";
38
39 _ = try imageFile.write(header);
40
41 for (0..(ImageSize * ImageSize)) |_| {
42 const color = Color.initRandom();
43 _ = try imageFile.write(color.toString());
44 }
45}