|
diff --git a/zig-ppm/main.zig b/zig-ppm/main.zig
|
|
|
1 |
// PPM image format - https://netpbm.sourceforge.net/doc/ppm.html |
|
|
2 |
|
|
|
3 |
const std = @import("std"); |
|
|
4 |
const debug = @import("std").debug; |
|
|
5 |
|
|
|
6 |
const ImageSize = 600; |
|
|
7 |
|
|
|
8 |
const 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 |
|
|
|
27 |
pub 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 |
} |