Skip to content

Commit

Permalink
write image data during build.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
trevarj committed Dec 25, 2022
1 parent 50540e4 commit 9687b60
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 35 deletions.
20 changes: 0 additions & 20 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ opt-level = 1
[dependencies]
anyhow = "1"
ggez = { version = "0.8.1", default-features = false }
include_dir = "0.7.3"
rand = "0.8.5"

[build-dependencies]
Expand Down
23 changes: 9 additions & 14 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::{Path, PathBuf};

use quote::__private::TokenStream;
use quote::{format_ident, quote};
Expand All @@ -18,11 +18,6 @@ fn main() {
// println!("cargo:warning={:#}", assets_struct.to_string());

assets_file.write_all(b"// @generated\n\n").unwrap();
assets_file.write_all(
quote! { static PROJECT_DIR: include_dir::Dir = include_dir::include_dir!("$CARGO_MANIFEST_DIR/assets"); }
.to_string()
.as_bytes(),
).unwrap();
assets_file
.write_all(assets_struct.to_string().as_bytes())
.expect("error writing struct to assets.rs file");
Expand All @@ -34,6 +29,10 @@ fn capitalize_first(s: &str) -> String {
.collect()
}

fn project_dir() -> PathBuf {
Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).to_path_buf()
}

fn visit_dir(path: &Path) -> (String, TokenStream) {
let mut fields = vec![];
let mut defs = vec![];
Expand All @@ -57,16 +56,12 @@ fn visit_dir(path: &Path) -> (String, TokenStream) {
.to_string()
);

let image_path = entry
.path()
.display()
.to_string()
.trim_start_matches("assets/")
.to_string();

let image_path = entry.path();
let image_path = project_dir().join(image_path);
let image_bytes = std::fs::read(&image_path).unwrap();
fields.push(quote! { pub #field_name : std::rc::Rc<ggez::graphics::Image> });
field_constructors
.push(quote! { #field_name: std::rc::Rc::new(ggez::graphics::Image::from_bytes(ctx, PROJECT_DIR.get_file(#image_path).unwrap().contents())?) })
.push(quote! { #field_name: std::rc::Rc::new(ggez::graphics::Image::from_bytes(ctx, &[ #(#image_bytes,)*])?) })
}
}
let struct_type = capitalize_first(&path.file_name().unwrap().to_string_lossy());
Expand Down

0 comments on commit 9687b60

Please sign in to comment.