diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6b39d31a96291e28ad5c033dc1267db1ff1b278d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +.idea/ \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..469dd3bf6365abfb584f9504433741886f1d0d76 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,920 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb07d2053ccdbe10e2af2995a2f116c1330396493dc1269f6a91d0ae82e19704" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "bit_field" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bumpalo" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" + +[[package]] +name = "bytemuck" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c53dfa917ec274df8ed3c572698f381a24eef2efba9492d797301b72b6db408a" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "3.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "190814073e85d238f31ff738fcb0bf6910cedeb73376c87cd69291028966fd83" +dependencies = [ + "atty", + "bitflags", + "clap_derive", + "clap_lex", + "indexmap", + "once_cell", + "strsim", + "termcolor", + "textwrap", +] + +[[package]] +name = "clap_derive" +version = "3.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759bf187376e1afa7b85b959e6a664a3e7a95203415dba952ad19139e798f902" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "crc32fast" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c02a4d71819009c192cf4872265391563fd6a84c81ff2c0f2a7026ca4c1d85c" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07db9d94cbd326813772c968ccd25999e5f8ae22f4f8d1b11effa37ef6ce281d" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "memoffset", + "once_cell", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d82ee10ce34d7bc12c2122495e7593a9c41347ecdd64185af4ecf72cb1a7f83" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "crunch" +version = "0.3.0" +dependencies = [ + "anyhow", + "clap", + "deltae", + "env_logger", + "glam", + "image", + "lab", + "log", + "num-traits", + "rayon", + "serde", + "serde_json", + "thiserror", + "toml", +] + +[[package]] +name = "deflate" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86f7e25f518f4b81808a2cf1c50996a61f5c2eb394b2393bd87f2a4780a432f" +dependencies = [ + "adler32", +] + +[[package]] +name = "deltae" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e412cd91a4ec62fcc739ea50c40babe21e3de60d69f36393cce377c7c04ead5a" + +[[package]] +name = "either" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f107b87b6afc2a64fd13cac55fe06d6c8859f12d4b14cbcdd2c67d0976781be" + +[[package]] +name = "env_logger" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "exr" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14cc0e06fb5f67e5d6beadf3a382fec9baca1aa751c6d5368fdeee7e5932c215" +dependencies = [ + "bit_field", + "deflate", + "flume", + "half", + "inflate", + "lebe", + "smallvec", + "threadpool", +] + +[[package]] +name = "flate2" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "flume" +version = "0.10.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ceeb589a3157cac0ab8cc585feb749bd2cea5cb55a6ee802ad72d9fd38303da" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "pin-project", + "spin", +] + +[[package]] +name = "futures-core" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" + +[[package]] +name = "futures-sink" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" + +[[package]] +name = "getrandom" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "glam" +version = "0.20.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f43e957e744be03f5801a55472f593d43fabdebf25a4585db250f04d86b1675f" + +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + +[[package]] +name = "hashbrown" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3" + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "image" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28edd9d7bc256be2502e325ac0628bde30b7001b9b52e0abe31a1a9dc2701212" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "exr", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits", + "png", + "scoped_threadpool", + "tiff", +] + +[[package]] +name = "indexmap" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "inflate" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cdb29978cc5797bd8dcc8e5bf7de604891df2a8dc576973d71a281e916db2ff" +dependencies = [ + "adler32", +] + +[[package]] +name = "itoa" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" + +[[package]] +name = "jpeg-decoder" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9478aa10f73e7528198d75109c8be5cd7d15fb530238040148d5f9a22d4c5b3b" +dependencies = [ + "rayon", +] + +[[package]] +name = "js-sys" +version = "0.3.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3fac17f7123a73ca62df411b1bf727ccc805daa070338fda671c86dac1bdc27" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "lebe" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7efd1d698db0759e6ef11a7cd44407407399a910c774dd804c64c032da7826ff" + +[[package]] +name = "libc" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" + +[[package]] +name = "lock_api" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" +dependencies = [ + "adler", +] + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "once_cell" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" + +[[package]] +name = "os_str_bytes" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21326818e99cfe6ce1e524c2a805c189a99b5ae555a35d19f9a284b427d86afa" + +[[package]] +name = "pin-project" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78203e83c48cffbe01e4a2d35d566ca4de445d79a85372fc64e378bfc812a260" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710faf75e1b33345361201d36d04e98ac1ed8909151a017ed384700836104c74" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "png" +version = "0.17.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc38c0ad57efb786dd57b9864e5b18bae478c00c824dc55a38bbc9da95dde3ba" +dependencies = [ + "bitflags", + "crc32fast", + "deflate", + "miniz_oxide", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rayon" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "regex" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" + +[[package]] +name = "ryu" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" + +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "serde" +version = "1.0.138" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1578c6245786b9d168c5447eeacfb96856573ca56c9d68fdcf394be134882a47" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.138" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023e9b1467aef8a10fb88f25611870ada9800ef7e22afce356bb0d2387b6f27c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "smallvec" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" + +[[package]] +name = "spin" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c530c2b0d0bf8b69304b39fe2001993e267461948b890cd037d8ad4293fa1a0d" +dependencies = [ + "lock_api", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "textwrap" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" + +[[package]] +name = "thiserror" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + +[[package]] +name = "tiff" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cfada0986f446a770eca461e8c6566cb879682f7d687c8348aa0c857bd52286" +dependencies = [ + "flate2", + "jpeg-decoder", + "weezl", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "unicode-ident" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c53b543413a17a202f4be280a7e5c62a1c69345f5de525ee64f8cfdbc954994" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5491a68ab4500fa6b4d726bd67408630c3dbe9c4fe7bda16d5c82a1fd8c7340a" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c441e177922bc58f1e12c022624b6216378e5febc2f0533e41ba443d505b80aa" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d94ac45fcf608c1f45ef53e748d35660f168490c10b23704c7779ab8f5c3048" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a89911bd99e5f3659ec4acf9c4d93b0a90fe4a2a11f15328472058edc5261be" + +[[package]] +name = "weezl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c97e489d8f836838d497091de568cf16b117486d529ec5579233521065bd5e4" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d76282808d4c901704bfe7b7f6c3e774582a386 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "crunch" +version = "0.3.0" +edition = "2021" + +[dependencies] +anyhow = "1.0.53" +clap = { version = "3.0.14", features = ["derive"] } +deltae = "0.3.0" +env_logger = "0.9.0" +glam = "0.20.5" +image = "0.24" +lab = "0.11.0" +log = "0.4.14" +num-traits = "0.2.14" +rayon = "1.5.1" +thiserror = "1.0.30" +serde = { version = "1.0.131", features = ["derive"] } +toml = "0.5.9" +serde_json = "1.0.81" diff --git a/README.md b/README.md index 486341b954667bce1dd848f3af9e4afd17b260cf..e4ff17d3a2590a29946ca7e4c5b25adb1c919b64 100644 --- a/README.md +++ b/README.md @@ -2,91 +2,39 @@ Command line image manipulation, set up a pipeline once and run it against all of your assets -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://lab.lcr.gr/microhacks/crunch.git -git branch -M trunk -git push -uf origin trunk -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://lab.lcr.gr/microhacks/crunch/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - ## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +Crunch takes an image and applies a transformation to it. But what if you want to do **two** transformations? +Or transform more than one image at a time? + +Pipelines! -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +The main value of Crunch is reproducible image processing, as defined by a [pipeline toml]() file. -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +Basic CLI usage: -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +```shell +USAGE: + crunch [OPTIONS] <IN_PATH> <OUT_PATH> <SUBCOMMAND> -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +ARGS: + <IN_PATH> The path to the spritesheet file + <OUT_PATH> The path to the output file -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +OPTIONS: + -f, --format <FORMAT> Force Crunch to read the input file as a specific format [possible + values: png, jpg, gif, ico, tga, tiff, bmp] + -h, --help Print help information + -V, --version Print version information -## License -For open source projects, say how it is licensed. +SUBCOMMANDS: + extrude Take each tile in an image and expand its borders by a given amount + flip Flip an image along one or both axis + help Print this message or the help of the given subcommand(s) + palette Create a palette file containing every distinct colour from the input image + pipeline Execute a pipeline file to run multiple commands on one or more images + remap Convert the colour space of an input image to the given palette + rotate Apply a clockwise rotation to the image + scale Make an image larger or smaller -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +``` diff --git a/src/cli_args.rs b/src/cli_args.rs new file mode 100644 index 0000000000000000000000000000000000000000..f551cd07a579aeb9424edb32353b99135124f34f --- /dev/null +++ b/src/cli_args.rs @@ -0,0 +1,167 @@ +use clap::{Parser, Subcommand}; +use serde::{Deserialize, Serialize}; + +use crate::commands::{ + calculate_mapping, execute_pipeline, extrude, flip, palette, remap_image, rescale, rotate, + write_palette, FlipDirection, RotateDegree, +}; +use crate::format::PaletteFormat; +use crate::{load_image, Format}; + +/// Image utilities for Advent +#[derive(Parser, Debug, Clone)] +#[clap(name = "Crunch")] +#[clap(author = "Louis Capitanchik <louis@microhacks.co.uk>")] +#[clap(version = "0.3.0")] +#[clap(about, long_about = None)] +pub struct Args { + /// The path to the spritesheet file + // #[clap(short = 'i', long = "in")] + in_path: String, + /// The path to the output file + // #[clap(short = 'o', long = "out")] + out_path: String, + + /// Force Crunch to read the input file as a specific format + #[clap(short, long, arg_enum)] + format: Option<Format>, + + #[clap(subcommand)] + command: CrunchCommand, +} + +#[inline] +pub fn u32_zero() -> u32 { + 0 +} +#[inline] +pub fn u32_32() -> u32 { + 32 +} +#[inline] +pub fn f32_one() -> f32 { + 1.0 +} + +#[derive(Debug, Clone, Subcommand, Serialize, Deserialize)] +#[serde(tag = "command", content = "params")] +pub enum CrunchCommand { + /// Take each tile in an image and expand its borders by a given amount + #[clap(version = "0.3.0")] + Extrude { + /// The amount of horizontal padding to add between each sprite in the image + #[clap(long, default_value_t = 0)] + #[serde(default = "u32_zero")] + space_x: u32, + /// The amount of vertical padding to add between each sprite in the image + #[clap(long, default_value_t = 0)] + #[serde(default = "u32_zero")] + space_y: u32, + /// The amount of horizontal padding to add between each sprite in the image + #[clap(long, default_value_t = 0)] + #[serde(default = "u32_zero")] + pad_x: u32, + /// The amount of vertical padding to add between each sprite in the image + #[clap(long, default_value_t = 0)] + #[serde(default = "u32_zero")] + pad_y: u32, + /// The size of each tile in the spritesheet. Assumed to be square tiles + #[clap(short, long, default_value_t = 32)] + #[serde(default = "u32_32")] + tile_size: u32, + /// Use nearby pixels for padding + #[clap(short, long)] + #[serde(default)] + extrude: bool, + }, + /// Create a palette file containing every distinct colour from the input image + #[clap(version = "0.3.0")] + Palette { + #[clap(short, long, arg_enum, default_value_t)] + #[serde(default)] + format: PaletteFormat, + }, + /// Convert the colour space of an input image to the given palette + #[clap(version = "0.3.0")] + Remap { + /// The path to the palette file containing the output colours + palette_file: String, + }, + /// Make an image larger or smaller + #[clap(version = "0.3.0")] + Scale { + /// The scale factor to use; numbers between 0-1 shrink the image; numbers > 1 enlarge + #[clap(long, default_value_t = 1.0)] + #[serde(default = "f32_one")] + factor: f32, + }, + /// Apply a clockwise rotation to the image + #[clap(version = "0.3.0")] + Rotate { + /// How many 90 degree steps should this image be rotated by + #[clap(long, arg_enum)] + amount: RotateDegree, + }, + /// Flip an image along one or both axis + #[clap(version = "0.3.0")] + Flip { + /// The axis along which the image should be flipped + #[clap(long, arg_enum)] + direction: FlipDirection, + }, + /// Execute a pipeline file to run multiple commands on one or more images + #[clap(version = "0.3.0")] + Pipeline, +} + +impl Args { + pub fn run(&self) -> anyhow::Result<()> { + match &self.command { + CrunchCommand::Extrude { + extrude: ext, + pad_x, + pad_y, + space_x, + space_y, + tile_size, + } => { + let image = load_image(&self.in_path, self.format)?; + let output = extrude(image, *tile_size, *pad_x, *pad_y, *space_x, *space_y, *ext)?; + output.save(&self.out_path).map_err(anyhow::Error::from) + } + CrunchCommand::Palette { format } => { + let image = load_image(&self.in_path, self.format)?; + let output = palette(&image)?; + write_palette(output, *format, &self.out_path) + } + CrunchCommand::Remap { palette_file } => { + let image_data = load_image(&self.in_path, self.format)?; + let palette_data = load_image(&palette_file, self.format)?; + + let image_palette = palette(&image_data)?; + let target_palette = palette(&palette_data)?; + + let mappings = calculate_mapping(&image_palette, &target_palette); + let output = remap_image(image_data, mappings)?; + + output.save(&self.out_path).map_err(anyhow::Error::from) + } + CrunchCommand::Scale { factor } => { + let image = load_image(self.in_path.clone(), self.format)?; + let output = rescale(&image, *factor)?; + output.save(&self.out_path).map_err(anyhow::Error::from) + } + CrunchCommand::Rotate { amount } => { + let image = load_image(self.in_path.clone(), self.format)?; + let output = rotate(&image, *amount)?; + output.save(&self.out_path).map_err(anyhow::Error::from) + } + CrunchCommand::Flip { direction } => { + let image = load_image(self.in_path.clone(), self.format)?; + let output = flip(&image, *direction)?; + output.save(&self.out_path).map_err(anyhow::Error::from) + } + CrunchCommand::Pipeline => execute_pipeline(&self.in_path, &self.out_path), + } + } +} diff --git a/src/commands/extrude.rs b/src/commands/extrude.rs new file mode 100644 index 0000000000000000000000000000000000000000..1229afd2025babadf130045005f1f0c22982555a --- /dev/null +++ b/src/commands/extrude.rs @@ -0,0 +1,88 @@ +use image::{GenericImage, GenericImageView, Pixel, Rgba, RgbaImage}; +use num_traits::cast::ToPrimitive; + +use crate::{OutputFormat, SpriteData}; + +pub fn extrude( + image: impl GenericImage, + tile_size: u32, + pad_x: u32, + pad_y: u32, + space_x: u32, + space_y: u32, + _extrude: bool, +) -> anyhow::Result<OutputFormat> { + log::info!( + "Image loaded with size {} x {}", + image.width(), + image.height() + ); + + let columns = image.width() / tile_size; + let rows = image.height() / tile_size; + log::info!("Inferred sheet contains {} columns", columns); + log::info!("Inferred sheet contains {} rows", rows); + + let mut views = Vec::with_capacity((columns * rows) as usize); + for x in 0..columns { + for y in 0..rows { + let img_x = x * tile_size; + let img_y = y * tile_size; + + let payload = SpriteData { + data: image.view(img_x, img_y, tile_size, tile_size), + x: img_x, + y: img_y, + tx: x, + ty: y, + width: tile_size, + height: tile_size, + }; + + views.push(payload); + } + } + + let new_width = (pad_x * 2 + space_x * columns) + image.width(); + let new_height = (pad_y * 2 + space_y * rows) + image.height(); + + log::info!( + "Using new image width {} / height {}", + new_width, + new_height + ); + let mut new_image = RgbaImage::new(new_width, new_height); + let (new_image_x, new_image_y, new_image_width, new_image_height) = new_image.bounds(); + for x in new_image_x..new_image_width { + for y in new_image_y..new_image_height { + new_image.put_pixel(x, y, Rgba::from([0, 0, 0, 0])); + } + } + + for sprite in views.iter() { + let (img_x, img_y, width, height) = sprite.data.bounds(); + for x in 0..width { + for y in 0..height { + let pix = sprite.data.get_pixel(x, y).to_rgba(); + let p = Rgba::from([ + pix.0[0].to_u8().unwrap(), + pix.0[1].to_u8().unwrap(), + pix.0[2].to_u8().unwrap(), + pix.0[3].to_u8().unwrap(), + ]); + + // log::info! + + new_image.put_pixel( + pad_x + (sprite.tx * space_x) + img_x + x, + pad_y + (sprite.ty * space_y) + img_y + y, + p, + ); + } + } + } + + log::info!("{}", new_image.width() * new_image.height()); + + Ok(new_image) +} diff --git a/src/commands/flip.rs b/src/commands/flip.rs new file mode 100644 index 0000000000000000000000000000000000000000..ea459d98f0040dbf6a10c3bfeae32e1be2fbec1d --- /dev/null +++ b/src/commands/flip.rs @@ -0,0 +1,34 @@ +use clap::ArgEnum; +use image::imageops::FilterType; +use image::{imageops, GenericImage, ImageBuffer, Pixel}; +use serde::{Deserialize, Serialize}; + +#[derive(Copy, Clone, Serialize, Deserialize, ArgEnum, Debug)] +pub enum FlipDirection { + #[serde(rename = "vertical")] + Vertical, + #[serde(rename = "horizontal")] + Horizontal, + #[serde(rename = "both")] + Both, +} + +pub fn flip<T: GenericImage>( + image: &T, + dir: FlipDirection, +) -> anyhow::Result<ImageBuffer<T::Pixel, Vec<<T::Pixel as Pixel>::Subpixel>>> +where + T::Pixel: 'static, + <T::Pixel as Pixel>::Subpixel: 'static, +{ + use FlipDirection::*; + match dir { + Vertical => Ok(imageops::flip_vertical(image)), + Horizontal => Ok(imageops::flip_horizontal(image)), + Both => { + let mut image = imageops::flip_horizontal(image); + imageops::flip_vertical_in_place(&mut image); + Ok(image) + } + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..be37ccd3cea104aa778091a5b261140f0f252dda --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,15 @@ +mod extrude; +mod flip; +mod palette; +mod pipeline; +mod remap; +mod rotate; +mod scale; + +pub use extrude::extrude; +pub use flip::{flip, FlipDirection}; +pub use palette::{calculate_mapping, palette, write_palette, ColourMapping}; +pub use pipeline::execute_pipeline; +pub use remap::remap_image; +pub use rotate::{rotate, RotateDegree}; +pub use scale::rescale; diff --git a/src/commands/palette.rs b/src/commands/palette.rs new file mode 100644 index 0000000000000000000000000000000000000000..88a23a90f1996522f2c00a339d551a3ad0e7db5e --- /dev/null +++ b/src/commands/palette.rs @@ -0,0 +1,181 @@ +use std::cmp::{min, Ordering}; +use std::collections::hash_map::RandomState; +use std::collections::{HashMap, HashSet}; +use std::fmt::{Formatter, LowerHex, UpperHex}; +use std::io::Write; +use std::path::Path; + +use deltae::{Delta, LabValue, DE2000}; +use image::{GenericImage, Pixel, Rgba}; +use num_traits::ToPrimitive; + +use crate::format::PaletteFormat; +use crate::utils::{new_image, BasicRgba}; + +pub type Palette = Vec<BasicRgba>; + +pub fn palette(image: &impl GenericImage) -> anyhow::Result<Palette> { + let mut colours = HashSet::new(); + for (_, _, pixel) in image.pixels().into_iter() { + let pixel = pixel.to_rgba(); + colours.insert(Rgba::from([ + pixel.0[0].to_u8().unwrap(), + pixel.0[1].to_u8().unwrap(), + pixel.0[2].to_u8().unwrap(), + pixel.0[3].to_u8().unwrap(), + // &pixel.0.map(|i| i.to_u8().unwrap()) + ])); + } + + Ok(colours.iter().map(|c| BasicRgba::from(c)).collect()) +} + +struct HexStringValue(String); +trait HexString { + fn as_hex_string(&self) -> HexStringValue; +} +impl HexString for Rgba<u8> { + fn as_hex_string(&self) -> HexStringValue { + HexStringValue(format!( + "{:02X}{:02X}{:02X}{:02X}", + self.0[0], self.0[1], self.0[2], self.0[3] + )) + } +} +impl<T: HexString + Clone> HexString for &T { + fn as_hex_string(&self) -> HexStringValue { + self.clone().as_hex_string() + } +} +impl UpperHex for HexStringValue { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0.to_uppercase()) + } +} +impl LowerHex for HexStringValue { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0.to_lowercase()) + } +} + +pub fn write_palette<T: AsRef<Path>>( + colours: Palette, + format: PaletteFormat, + outpath: T, +) -> anyhow::Result<()> { + let mut sorted = colours.clone(); + sorted.sort_by(|pa, pb| { + // format!("{:X}", pa.as_hex_string()) + // .cmp(&format!("{:X}", pb.as_hex_string())) + + let hue_a = pa.hue(); + let hue_b = pb.hue(); + + println!("A: {} vs B: {}", hue_a, hue_b); + + if hue_a > hue_b { + Ordering::Greater + } else if hue_b > hue_a { + Ordering::Less + } else { + Ordering::Equal + } + }); + + match format { + PaletteFormat::PNG => { + let num_colours = sorted.len(); + let image_width = min(16, num_colours); + let image_height = if num_colours % 16 > 0 { + num_colours / image_width + 1 + } else { + num_colours / image_width + }; + + let mut out_image = new_image(image_width as u32, image_height as u32); + for (idx, colour) in sorted.iter().enumerate() { + out_image.put_pixel( + (idx % image_width) as u32, + (idx / image_width) as u32, + Rgba::from(colour), + ); + } + + out_image.save(outpath)?; + } + PaletteFormat::TXT => { + let mut file = std::fs::File::create(outpath)?; + for colour in sorted.iter() { + let line = format!("#{:X}\n", colour); + file.write_all(line.as_bytes())?; + } + } + } + + Ok(()) +} + +pub type ColourMapping = HashMap<BasicRgba, BasicRgba>; + +pub fn calculate_mapping(from: &Palette, to: &Palette) -> ColourMapping { + let colour_labs = Vec::from_iter(to.iter().map(LabValue::from)); + + let to_palette_vectors: HashMap<usize, &BasicRgba, RandomState> = + HashMap::from_iter(to.iter().enumerate()); + let mut out_map: ColourMapping = HashMap::with_capacity(from.len()); + + for colour in from { + let closest = to_palette_vectors + .keys() + .fold(None, |lowest, idx| match lowest { + Some(num) => { + let current = colour_labs[*idx]; + let previous: LabValue = colour_labs[num]; + + if colour.delta(current, DE2000) < colour.delta(previous, DE2000) { + Some(*idx) + } else { + Some(num) + } + } + None => Some(*idx), + }); + + match closest { + Some(idx) => match to_palette_vectors.get(&idx) { + Some(col) => { + out_map.insert(colour.clone(), *col.clone()); + } + None => { + println!("No matching vec for {} with col {:?}", idx, &colour); + + out_map.insert( + colour.clone(), + BasicRgba { + r: 0, + g: 0, + b: 0, + a: 0, + }, + ); + } + }, + None => { + println!("No closest for {:?}", &colour); + out_map.insert( + colour.clone(), + BasicRgba { + r: 0, + g: 0, + b: 0, + a: 0, + }, + ); + } + } + } + + // println!("{:?}", &out_map); + + out_map +} diff --git a/src/commands/pipeline.rs b/src/commands/pipeline.rs new file mode 100644 index 0000000000000000000000000000000000000000..2b3aca2692abf71e936b72fce77bfa9833564f0d --- /dev/null +++ b/src/commands/pipeline.rs @@ -0,0 +1,243 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use rayon::prelude::*; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use crate::cli_args::CrunchCommand; +use crate::utils::Pipeline; +use crate::{commands, load_image}; + +#[derive(Error, Debug)] +pub enum PipelineError { + #[error("Use a file ending with '.toml' or '.json' to configure your pipeline")] + FormatDetection, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PipelineType { + Pipeline { + input_path: String, + output_path: String, + actions: Vec<crate::cli_args::CrunchCommand>, + }, + Ref { + input_path: String, + output_path: String, + reference: String, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PipelineRef { + pub actions: Vec<crate::cli_args::CrunchCommand>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PipelineFile { + pub refs: HashMap<String, PipelineRef>, + pub pipelines: Vec<PipelineType>, +} + +pub fn execute_pipeline<IN: ToString, OUT: ToString>( + file_path: IN, + _outpath: OUT, +) -> anyhow::Result<()> { + let path = file_path.to_string(); + if !&path.ends_with(".toml") && !&path.ends_with(".json") { + Err(PipelineError::FormatDetection)?; + } + + let file_contents = std::fs::read(file_path.to_string())?; + let mut pipeline_data: PipelineFile = if path.ends_with(".toml") { + toml::from_slice(&file_contents)? + } else { + serde_json::from_slice(&file_contents)? + }; + + pipeline_data + .pipelines + .par_iter() + .filter_map(|pipe| match pipe { + PipelineType::Pipeline { + input_path, + output_path, + actions, + } => Some((input_path, output_path, actions.clone())), + PipelineType::Ref { + input_path, + output_path, + reference, + } => pipeline_data + .refs + .get(reference) + .map(|value| (input_path, output_path, value.actions.clone())), + }) + .for_each(|(input_path, output_path, actions)| { + let mut file = match load_image(input_path, None) { + Ok(image) => image, + Err(e) => { + log::error!("Error loading {}; {:?}", input_path, e); + return; + } + }; + + let mut count = 1; + let total = actions.len(); + + for step in actions { + match step { + CrunchCommand::Extrude { + tile_size, + space_y, + space_x, + pad_y, + pad_x, + extrude, + } => { + file = match commands::extrude( + file, tile_size, pad_x, pad_y, space_x, space_y, extrude, + ) { + Ok(f) => f, + Err(e) => { + log::error!( + "Failed to extrude {} at step {}; {}", + input_path, + count, + e + ); + return; + } + }; + } + CrunchCommand::Remap { palette_file } => { + let palette_data = match load_image(&palette_file, None) { + Ok(p) => p, + Err(e) => { + log::error!( + "Failed to load {} at step {}; {:?}", + input_path, + count, + e + ); + return; + } + }; + + let image_palette = match commands::palette(&file) { + Ok(ip) => ip, + Err(e) => { + log::error!( + "Failed to extract palette from {} at step {}; {}", + input_path, + count, + e + ); + return; + } + }; + + let target_palette = match commands::palette(&palette_data) { + Ok(tp) => tp, + Err(e) => { + log::error!( + "Failed to extract palette from {} at step {}; {}", + &palette_file, + count, + e + ); + return; + } + }; + + let mappings = commands::calculate_mapping(&image_palette, &target_palette); + file = match commands::remap_image(file, mappings) { + Ok(f) => f, + Err(e) => { + log::error!( + "Failed to remap {} at step {}; {}", + input_path, + count, + e + ); + return; + } + }; + } + CrunchCommand::Scale { factor } => { + file = match commands::rescale(&file, factor) { + Ok(f) => f, + Err(e) => { + log::error!( + "Failed to scale {} at step {}; {}", + input_path, + count, + e + ); + return; + } + }; + } + CrunchCommand::Rotate { amount } => { + file = match commands::rotate(&file, amount) { + Ok(f) => f, + Err(e) => { + log::error!( + "Failed to rotate {} by {:?} step(s); {}", + input_path, + amount, + e + ); + return; + } + }; + } + CrunchCommand::Flip { direction } => { + file = match commands::flip(&file, direction) { + Ok(f) => f, + Err(e) => { + log::error!( + "Failed to flip {} in the following direction: {:?}; {}", + input_path, + direction, + e + ); + return; + } + }; + } + CrunchCommand::Palette { .. } | CrunchCommand::Pipeline => continue, + } + + count += 1; + } + + let mut outer_target_path = PathBuf::from(output_path); + outer_target_path.pop(); + + match std::fs::create_dir(&outer_target_path) { + Err(e) => match e.kind() { + std::io::ErrorKind::AlreadyExists => { /* This is fine */ } + _ => log::error!( + "Failed to create containing directory {}; {}", + outer_target_path.to_string_lossy(), + e + ), + }, + _ => {} + } + + match file.save(output_path) { + Ok(_) => {} + Err(e) => { + log::error!("Failed to save to {}; {}", output_path, e); + return; + } + } + }); + + Ok(()) +} diff --git a/src/commands/remap.rs b/src/commands/remap.rs new file mode 100644 index 0000000000000000000000000000000000000000..d9062fb15989b6c74ff501060ba3688dde3946ae --- /dev/null +++ b/src/commands/remap.rs @@ -0,0 +1,43 @@ +use image::{GenericImage, Pixel, Rgba}; +use num_traits::ToPrimitive; + +use crate::commands::ColourMapping; +use crate::utils::{new_image, BasicRgba}; +use crate::OutputFormat; + +pub fn remap_image( + image: impl GenericImage, + mappings: ColourMapping, +) -> anyhow::Result<OutputFormat> { + let mut output = new_image(image.width(), image.height()); + for (x, y, pixel) in image.pixels().into_iter() { + let pixel = pixel.to_rgba(); + + if pixel.0[3].to_u8().unwrap() == 0 { + output.put_pixel(x, y, Rgba::from(BasicRgba::transparent())); + continue; + } + + let data = Rgba::from([ + pixel.0[0].to_u8().unwrap(), + pixel.0[1].to_u8().unwrap(), + pixel.0[2].to_u8().unwrap(), + pixel.0[3].to_u8().unwrap(), + ]); + let basic = BasicRgba::from(data); + + match mappings.get(&basic) { + Some(mapped_data) => output.put_pixel( + x, + y, + Rgba::from(BasicRgba { + a: basic.a, + ..mapped_data.clone() + }), + ), + None => output.put_pixel(x, y, Rgba::from(BasicRgba::transparent())), + }; + } + + Ok(output) +} diff --git a/src/commands/rotate.rs b/src/commands/rotate.rs new file mode 100644 index 0000000000000000000000000000000000000000..df6858638cf7036b90063336f846e4231817e49e --- /dev/null +++ b/src/commands/rotate.rs @@ -0,0 +1,30 @@ +use clap::ArgEnum; +use image::imageops::FilterType; +use image::{imageops, GenericImage, ImageBuffer, Pixel}; +use serde::{Deserialize, Serialize}; + +#[derive(Copy, Clone, Serialize, Deserialize, ArgEnum, Debug)] +pub enum RotateDegree { + #[serde(rename = "90")] + One, + #[serde(rename = "180")] + Two, + #[serde(rename = "270")] + Three, +} + +pub fn rotate<T: GenericImage>( + image: &T, + degree: RotateDegree, +) -> anyhow::Result<ImageBuffer<T::Pixel, Vec<<T::Pixel as Pixel>::Subpixel>>> +where + T::Pixel: 'static, + <T::Pixel as Pixel>::Subpixel: 'static, +{ + use RotateDegree::*; + match degree { + One => Ok(imageops::rotate90(image)), + Two => Ok(imageops::rotate180(image)), + Three => Ok(imageops::rotate270(image)), + } +} diff --git a/src/commands/scale.rs b/src/commands/scale.rs new file mode 100644 index 0000000000000000000000000000000000000000..db8a2cb31f751005d158bfed7af05ecb2cb8a1a8 --- /dev/null +++ b/src/commands/scale.rs @@ -0,0 +1,21 @@ +use image::imageops::FilterType; +use image::{imageops, GenericImage, ImageBuffer, Pixel}; + +pub fn rescale<T: GenericImage>( + image: &T, + factor: f32, +) -> anyhow::Result<ImageBuffer<T::Pixel, Vec<<T::Pixel as Pixel>::Subpixel>>> +where + T::Pixel: 'static, + <T::Pixel as Pixel>::Subpixel: 'static, +{ + let nwidth = (image.width() as f32 * factor) as u32; + let nheight = (image.height() as f32 * factor) as u32; + + Ok(imageops::resize( + image, + nwidth, + nheight, + FilterType::Nearest, + )) +} diff --git a/src/format.rs b/src/format.rs new file mode 100644 index 0000000000000000000000000000000000000000..b0274e707f9225689eb438b0a246ba7509f2db29 --- /dev/null +++ b/src/format.rs @@ -0,0 +1,72 @@ +use std::path::Path; + +use clap::ArgEnum; +use image::io::Reader; +use image::{ImageError, ImageFormat, RgbaImage}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive( + Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum, Debug, Serialize, Deserialize, Default, +)] +pub enum PaletteFormat { + TXT, + #[default] + PNG, +} + +// impl Default for PaletteFormat { +// fn default() -> Self { +// Self::PNG +// } +// } + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum, Debug)] +pub enum Format { + PNG, + JPG, + GIF, + ICO, + TGA, + TIFF, + BMP, +} + +impl Format { + pub fn as_image_format(&self) -> ImageFormat { + use Format::*; + match self { + PNG => ImageFormat::Png, + JPG => ImageFormat::Jpeg, + GIF => ImageFormat::Gif, + ICO => ImageFormat::Ico, + TGA => ImageFormat::Tga, + TIFF => ImageFormat::Tiff, + BMP => ImageFormat::Bmp, + } + } +} + +#[derive(Error, Debug)] +pub enum ImageLoadingError { + #[error("Failed to load image data; {0}")] + IoError(#[from] std::io::Error), + #[error("Failed to process image; {0}")] + ImageError(#[from] ImageError), +} + +pub fn load_image<T: AsRef<Path>>( + path: T, + format: Option<Format>, +) -> anyhow::Result<RgbaImage, ImageLoadingError> { + let mut image = Reader::open(path)?; + let file = match format { + Some(format) => { + image.set_format(format.as_image_format()); + image.decode()?.into_rgba8() + } + None => image.with_guessed_format()?.decode()?.into_rgba8(), + }; + + Ok(file) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..2dd3fb8d4dd7be7db6c2ff0c22c27594f97096a2 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,34 @@ +mod cli_args; +mod commands; +mod format; +mod utils; + +use clap::Parser; +use image::{GenericImage, Rgba, SubImage}; + +use crate::cli_args::Args; +use crate::format::{load_image, Format}; + +#[derive(Clone, Copy)] +struct SpriteData<'a, T: GenericImage> { + pub data: SubImage<&'a T>, + #[allow(dead_code)] + pub x: u32, + #[allow(dead_code)] + pub y: u32, + pub tx: u32, + pub ty: u32, + #[allow(dead_code)] + pub width: u32, + #[allow(dead_code)] + pub height: u32, +} + +pub type OutputFormat = image::ImageBuffer<Rgba<u8>, Vec<u8>>; + +fn main() -> anyhow::Result<(), anyhow::Error> { + env_logger::Builder::from_env("LOG_LEVEL").init(); + let args: Args = Args::parse(); + args.run()?; + Ok(()) +} diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000000000000000000000000000000000000..6048aa40bbe4a50e9e481825846f48ebc73bea46 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,251 @@ +use std::fmt::{Formatter, LowerHex, UpperHex}; + +use deltae::LabValue; +use glam::Vec3; +use image::{GenericImageView, Rgb, Rgba, RgbaImage}; +use lab::Lab; +use serde::{Deserialize, Serialize}; + +use crate::OutputFormat; + +pub fn max_f32(a: f32, b: f32) -> f32 { + if a > b { + a + } else { + b + } +} + +pub fn min_f32(a: f32, b: f32) -> f32 { + if a < b { + a + } else { + b + } +} + +pub fn new_image(new_width: u32, new_height: u32) -> OutputFormat { + let mut new_image = RgbaImage::new(new_width, new_height); + let (new_image_x, new_image_y, new_image_width, new_image_height) = new_image.bounds(); + for x in new_image_x..new_image_width { + for y in new_image_y..new_image_height { + new_image.put_pixel(x, y, Rgba::from([0, 0, 0, 0])); + } + } + new_image +} + +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub struct BasicRgba { + pub r: u8, + pub g: u8, + pub b: u8, + pub a: u8, +} + +impl BasicRgba { + pub fn hue(&self) -> f32 { + let red = self.r as f32 / u8::MAX as f32; + let green = self.g as f32 / u8::MAX as f32; + let blue = self.b as f32 / u8::MAX as f32; + + let minimum = min_f32(red, min_f32(green, blue)); + let maximum = max_f32(red, max_f32(green, blue)); + + let mut hue = if red >= green && red >= blue { + (green - blue) / (maximum - minimum) + } else if green >= red && green >= blue { + 2.0 + (blue - red) / (maximum - minimum) + } else { + 4.0 + (red - green) / (maximum - minimum) + }; + + hue *= 60.0; + + while hue < 0.0 { + hue += 360.0; + } + + hue + } + + pub fn transparent() -> Self { + Self { + r: 0, + g: 0, + b: 0, + a: 0, + } + } +} + +impl From<Rgba<u8>> for BasicRgba { + fn from(other: Rgba<u8>) -> Self { + Self { + r: other.0[0], + g: other.0[1], + b: other.0[2], + a: other.0[3], + } + } +} +impl From<&Rgba<u8>> for BasicRgba { + fn from(other: &Rgba<u8>) -> Self { + Self { + r: other.0[0], + g: other.0[1], + b: other.0[2], + a: other.0[3], + } + } +} + +impl From<Rgb<u8>> for BasicRgba { + fn from(other: Rgb<u8>) -> Self { + Self { + r: other.0[0], + g: other.0[1], + b: other.0[2], + a: u8::MAX, + } + } +} +impl From<&Rgb<u8>> for BasicRgba { + fn from(other: &Rgb<u8>) -> Self { + Self { + r: other.0[0], + g: other.0[1], + b: other.0[2], + a: u8::MAX, + } + } +} + +impl From<BasicRgba> for Rgba<u8> { + fn from(other: BasicRgba) -> Self { + Self::from([other.r, other.g, other.b, other.a]) + } +} +impl From<&BasicRgba> for Rgba<u8> { + fn from(other: &BasicRgba) -> Self { + Self::from([other.r, other.g, other.b, other.a]) + } +} +impl From<BasicRgba> for Rgb<u8> { + fn from(other: BasicRgba) -> Self { + Self::from([other.r, other.g, other.b]) + } +} +impl From<&BasicRgba> for Rgb<u8> { + fn from(other: &BasicRgba) -> Self { + Self::from([other.r, other.g, other.b]) + } +} + +impl From<BasicRgba> for LabValue { + fn from(other: BasicRgba) -> Self { + let converted = lab::Lab::from_rgb(&[other.r, other.g, other.b]); + + LabValue { + l: converted.l, + a: converted.a, + b: converted.b, + } + } +} +impl From<&BasicRgba> for LabValue { + fn from(other: &BasicRgba) -> Self { + let converted = lab::Lab::from_rgb(&[other.r, other.g, other.b]); + + LabValue { + l: converted.l, + a: converted.a, + b: converted.b, + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct BasicLab { + pub l: f32, + pub a: f32, + pub b: f32, +} + +impl From<LabValue> for BasicLab { + fn from(other: LabValue) -> Self { + Self { + l: other.l, + a: other.a, + b: other.b, + } + } +} + +impl From<BasicLab> for LabValue { + fn from(other: BasicLab) -> Self { + Self { + l: other.l, + a: other.a, + b: other.b, + } + } +} + +impl From<BasicLab> for Lab { + fn from(other: BasicLab) -> Self { + Self { + l: other.l, + a: other.a, + b: other.b, + } + } +} + +impl From<BasicLab> for BasicRgba { + fn from(other: BasicLab) -> Self { + let lab: Lab = other.into(); + let vals = lab.to_rgb(); + Self { + r: vals[0], + g: vals[1], + b: vals[2], + a: u8::MAX, + } + } +} + +impl From<BasicRgba> for Vec3 { + fn from(other: BasicRgba) -> Self { + Vec3::new(other.r as f32, other.g as f32, other.b as f32) + } +} +impl From<BasicLab> for Vec3 { + fn from(other: BasicLab) -> Self { + Vec3::new(other.l, other.a, other.b) + } +} + +impl UpperHex for BasicRgba { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&format!( + "{:2X}{:2X}{:2X}{:2X}", + self.r, self.g, self.b, self.a + )) + } +} +impl LowerHex for BasicRgba { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&format!( + "{:2x}{:2x}{:2x}{:2x}", + self.r, self.g, self.b, self.a + )) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Pipeline { + pub input_path: String, + pub output_path: String, + pub actions: Vec<crate::cli_args::CrunchCommand>, +}