code_generation/generate_image_info

Code

generate_image_info.odin ¶
83 linesSource

1/*
2This program generates `images.odin` by going through the `images` folder and
3opening each file. From each PNG file in there it will:
4
5- Generate a pretty enum name for it
6- Make a list of images where it maps each pretty enum name to an Image struct
7- The Image struct contains the width and the height. This is determined by
8    opening the PNG files.
9- The Image struct also contains a `data = #load(THE_FILENAME)` field. That will
10    make the compiler that later tries to compile `images.odin` load the file
11    data at compile-time.
12*/
13package generate_image_info
14
15import "core:os"
16import "core:strings"
17import "core:fmt"
18import "core:path/slashpath"
19import "core:image/png"
20import "core:image"
21
22// Avoids 'unused import' error: "core:image/png" needs to be imported in order
23// to make `img.load_from_bytes` understand PNG format.
24_ :: png
25
26INPUT_DIR :: "images"
27OUTPUT_FILE :: "images.odin"
28
29main :: proc() {
30	d, d_err := os.open(INPUT_DIR)
31	assert(d_err == nil, "Failed opening '" + INPUT_DIR + "' folder")
32	defer os.close(d)
33
34	input_files, _ := os.read_dir(d, -1, context.allocator)
35
36	f, _ := os.open(OUTPUT_FILE, {.Write, .Create, .Trunc}, {.Write_User, .Read_Other, .Read_Group})
37	defer os.close(f)
38
39	images: [dynamic]os.File_Info
40
41	for i in input_files {
42		if !strings.has_suffix(i.name, ".png") {
43			continue
44		}
45
46		append(&images, i)
47	}
48
49	fmt.fprintln(f,
50`// This file is generated. Re-generate it by running:
51//	odin run generate_image_info
52package image_viewer
53
54Image :: struct {
55	width: int,
56	height: int,
57	data: []u8,
58}
59
60Image_Name :: enum {`,
61)
62
63	for i in images {
64		fmt.fprintfln(f, "	%v,", strings.to_ada_case(slashpath.name(i.name)))
65	}
66
67	fmt.fprintln(f,
68`}
69
70images := [Image_Name]Image {`,
71)
72
73	for i in images {
74		img, img_err := image.load_from_file(i.fullpath)
75
76		if img_err == nil {
77			enum_name := strings.to_ada_case(slashpath.name(i.name))
78			fmt.fprintfln(f, "	.%v = {{ data = #load(\"images/%v\"), width = %v, height = %v }},", enum_name, i.name, img.width, img.height)
79		}
80	}
81
82	fmt.fprintln(f, "}")
83}

Declarations Used 10