librashader-cli 0.12.0

RetroArch shaders for all.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
use anyhow::anyhow;
use clap::{Parser, Subcommand};
use image::codecs::png::PngEncoder;
use librashader::presets::context::ContextItem;
use librashader::presets::{ShaderFeatures, ShaderPreset, ShaderPresetPack, WildcardContext};
use librashader::reflect::cross::{GlslVersion, HlslShaderModel, MslVersion, SpirvCross};
use librashader::reflect::naga::{Naga, NagaLoweringOptions};
use librashader::reflect::semantics::ShaderSemantics;
use librashader::reflect::{CompileShader, FromCompilation, ReflectShader, SpirvCompilation};
use librashader::runtime::{ColorSpace, Size};
use librashader::{FastHashMap, ShortString};
use librashader_runtime::parameters::RuntimeParameters;
use librashader_test::render::{CommonFrameOptions, RenderTest};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Helpers and utilities to reflect and debug 'slang' shaders and presets.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Args {
    #[command(subcommand)]
    command: Commands,
}

#[derive(clap::Args, Debug)]
struct PresetArgs {
    /// The path to the shader preset to load.
    #[arg(short, long)]
    preset: PathBuf,
    /// Additional wildcard options, comma separated with equals signs. The PRESET and PRESET_DIR
    /// wildcards are always added to the preset parsing context.
    ///
    /// For example, CONTENT-DIR=MyVerticalGames,GAME=mspacman
    #[arg(short, long, value_delimiter = ',', num_args = 1..)]
    wildcards: Option<Vec<String>>,
}

#[derive(clap::Args, Debug)]
struct ShaderFeatureArgs {
    /// Enable the defines for certain shader features.
    ///
    /// `originalaspect-uniforms` defines `_HAS_ORIGINALASPECT_UNIFORMS`.
    /// `frametime-uniforms` defines `_HAS_FRAMETIME_UNIFORMS`.
    ///
    /// Note that defines will disappear in the final output, and are only passed for reflection.
    #[arg(long, short = 'd')]
    features: Vec<ShaderDefinesEnums>,
}

#[derive(clap::Args, Debug)]
struct RenderArgs {
    /// The frame to render.
    ///
    /// The renderer will run up to the number of frames specified here
    /// to ensure feedback and history.
    #[arg(short, long, default_value_t = 0)]
    frame: usize,
    /// The dimensions of the image.
    ///
    /// This is given in either explicit dimensions `WIDTHxHEIGHT`, or a
    /// percentage of the input image in `SCALE%`.
    #[arg(short, long)]
    dimensions: Option<String>,
    /// Parameters to pass to the shader preset, comma separated with equals signs.
    ///
    /// For example, crt_gamma=2.5,halation_weight=0.001
    #[arg(long, value_delimiter = ',', num_args = 1..)]
    params: Option<Vec<String>>,
    /// Set the number of passes enabled for the preset.
    #[arg(long)]
    passes_enabled: Option<usize>,
    /// The path to the input image.
    #[arg(short, long)]
    image: PathBuf,
    #[clap(flatten)]
    options: Option<FrameOptionsArgs>,
}

impl From<FrameOptionsArgs> for CommonFrameOptions {
    fn from(value: FrameOptionsArgs) -> Self {
        Self {
            clear_history: false,
            frame_direction: value.frame_direction,
            rotation: value.rotation,
            total_subframes: value.total_subframes,
            current_subframe: value.current_subframe,
            aspect_ratio: value.aspect_ratio.unwrap_or(0.0),
            frametime_delta: value.frametime_delta.unwrap_or(0),
            frames_per_second: value.frames_per_second.unwrap_or(1.0),
            color_space: value.color_space.into(),
            brightness_nits: value.brightness_nits.unwrap_or(200.0),
            expand_gamut: value.expand_gamut.unwrap_or(0),
            gyroscope: value.gyroscope.map(vec3_from_args).unwrap_or([0.0; 3]),
            accelerometer: value.accelerometer.map(vec3_from_args).unwrap_or([0.0; 3]),
            accelerometer_rest: value
                .accelerometer_rest
                .map(vec3_from_args)
                .unwrap_or([0.0; 3]),
            ..Default::default()
        }
    }
}

/// Collapse a `num_args = 3` value list into a fixed `[f32; 3]`.
///
/// clap guarantees exactly three values are present, so any missing
/// component falls back to 0.
fn vec3_from_args(values: Vec<f32>) -> [f32; 3] {
    [
        values.first().copied().unwrap_or(0.0),
        values.get(1).copied().unwrap_or(0.0),
        values.get(2).copied().unwrap_or(0.0),
    ]
}

impl From<ShaderFeatureArgs> for ShaderFeatures {
    fn from(value: ShaderFeatureArgs) -> Self {
        let mut features = ShaderFeatures::NONE;

        for feature in value.features {
            if matches!(feature, ShaderDefinesEnums::FrametimeUniforms) {
                features |= ShaderFeatures::FRAMETIME_UNIFORMS;
            }
            if matches!(feature, ShaderDefinesEnums::OriginalAspectUniforms) {
                features |= ShaderFeatures::ORIGINAL_ASPECT_UNIFORMS;
            }
        }

        features
    }
}

#[derive(clap::Args, Debug)]
struct FrameOptionsArgs {
    /// The direction of rendering.
    /// -1 indicates that the frames are played in reverse order.
    #[arg(long, default_value_t = 1, allow_hyphen_values = true)]
    pub frame_direction: i32,
    /// The rotation of the output. 0 = 0deg, 1 = 90deg, 2 = 180deg, 3 = 270deg.
    #[arg(long, default_value_t = 0)]
    pub rotation: u32,
    /// The total number of subframes ran. Default is 1.
    #[arg(long, default_value_t = 1)]
    pub total_subframes: u32,
    /// The current sub frame. Default is 1.
    #[arg(long, default_value_t = 1)]
    pub current_subframe: u32,
    /// The aspect ratio of the source. The default is 0, which will infer the ratio from the input.
    #[arg(long)]
    pub aspect_ratio: Option<f32>,
    /// Frames per second of the source. The default is 1.
    #[arg(long)]
    pub frames_per_second: Option<f32>,
    /// The time between the previous and current frame. The default is 0.
    #[arg(long)]
    pub frametime_delta: Option<u32>,
    /// The target color space for HDR shaders. The default is `sdr`.
    #[arg(long, value_enum, default_value_t = ColorSpaceArg::Sdr)]
    pub color_space: ColorSpaceArg,
    /// The HDR SDR reference white in nits. The default is 200.
    #[arg(long)]
    pub brightness_nits: Option<f32>,
    /// The gamut expansion mode for HDR shaders. The default is 0.
    #[arg(long)]
    pub expand_gamut: Option<u32>,
    /// The three-axis gyroscope reading for shaders that use gyroscope data.
    /// The default is 0 0 0.
    #[arg(long, num_args = 3, value_names = ["X", "Y", "Z"])]
    pub gyroscope: Option<Vec<f32>>,
    /// The three-axis accelerometer reading for shaders that use accelerometer data.
    /// The default is 0 0 0.
    #[arg(long, num_args = 3, value_names = ["X", "Y", "Z"])]
    pub accelerometer: Option<Vec<f32>>,
    /// The accelerometer reading at for shaders that use accelerometer data.
    /// The default is 0 0 0.
    #[arg(long, num_args = 3, value_names = ["X", "Y", "Z"])]
    pub accelerometer_rest: Option<Vec<f32>>,
}

#[derive(clap::ValueEnum, Clone, Copy, Debug)]
enum ColorSpaceArg {
    #[clap(name = "sdr")]
    Sdr,
    #[clap(name = "hdr10")]
    Hdr10,
    #[clap(name = "scrgb")]
    ScRgb,
    #[clap(name = "pq-scrgb")]
    PqScRgb,
}

impl From<ColorSpaceArg> for ColorSpace {
    fn from(value: ColorSpaceArg) -> Self {
        match value {
            ColorSpaceArg::Sdr => ColorSpace::Sdr,
            ColorSpaceArg::Hdr10 => ColorSpace::Hdr10,
            ColorSpaceArg::ScRgb => ColorSpace::ScRgb,
            ColorSpaceArg::PqScRgb => ColorSpace::PqScRgb,
        }
    }
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Render a shader preset against an image
    Render {
        #[clap(flatten)]
        preset: PresetArgs,
        #[clap(flatten)]
        render: RenderArgs,
        /// The path to the output image
        ///
        /// If `-`, writes the image in PNG format to stdout.
        #[arg(short, long)]
        out: PathBuf,
        /// The runtime to use to render the shader preset.
        #[arg(value_enum, short, long)]
        runtime: Runtime,
    },
    /// Compare two runtimes and get a similarity score between the two
    /// runtimes rendering the same frame
    Compare {
        #[clap(flatten)]
        preset: PresetArgs,
        #[clap(flatten)]
        render: RenderArgs,
        /// The runtime to compare against
        #[arg(value_enum, short, long)]
        left: Runtime,
        /// The runtime to compare to
        #[arg(value_enum, short, long)]
        right: Runtime,
        /// The path to write the similarity image.
        ///
        /// If `-`, writes the image to stdout.
        #[arg(short, long)]
        out: Option<PathBuf>,
    },
    /// Parse a preset and get a JSON representation of the data.
    Parse {
        #[clap(flatten)]
        preset: PresetArgs,
        #[clap(flatten)]
        flags: ShaderFeatureArgs,
    },
    /// Create a serialized preset pack from a shader preset.
    Pack {
        #[clap(flatten)]
        preset: PresetArgs,
        #[clap(flatten)]
        flags: ShaderFeatureArgs,
        /// The path to write the output
        ///
        /// If `-`, writes the output to stdout
        #[arg(short, long)]
        out: PathBuf,
        /// The file format to output.
        #[arg(value_enum, short, long)]
        format: PackFormat,

        #[arg(value_enum, short, long, default_value_t = PackShaderLanguage::GLSL)]
        language: PackShaderLanguage,
    },
    /// Get the raw GLSL output of a preprocessed shader.
    Preprocess {
        /// The path to the slang shader.
        #[arg(short, long)]
        shader: PathBuf,
        /// The item to output.
        ///
        /// `json` will print a JSON representation of the preprocessed shader.
        #[arg(value_enum, short, long)]
        output: PreprocessOutput,
        #[clap(flatten)]
        flags: ShaderFeatureArgs,
    },
    /// Transpile a shader to the given format.
    Transpile {
        /// The path to the slang shader.
        #[arg(short, long)]
        shader: PathBuf,

        /// The shader stage to output
        #[arg(value_enum, short = 'o', long)]
        stage: TranspileStage,

        /// The output format.
        #[arg(value_enum, short, long)]
        format: TranspileFormat,

        /// The version of the output format to parse as, if applicable
        ///
        /// For GLSL, this should be an string corresponding to a GLSL version (e.g. '330', or '300es', or '300 es').
        ///
        /// For HLSL, this is a shader model version as an integer (50), or a version in the format MAJ_MIN (5_0), or MAJ.MIN (5.0).
        ///
        /// For MSL, this is the shader language version as an integer in format
        /// <MMmmpp>(30100), or a version in the format MAJ_MIN (3_1), or MAJ.MIN (3.1).
        ///
        /// For SPIR-V, if this is the string "raw-id", then shows raw ID values instead of friendly names.
        #[arg(short, long)]
        version: Option<String>,
        #[clap(flatten)]
        flags: ShaderFeatureArgs,
    },
    /// Reflect the shader relative to a preset, giving information about semantics used in a slang shader.
    Reflect {
        #[clap(flatten)]
        preset: PresetArgs,

        #[clap(flatten)]
        flags: ShaderFeatureArgs,

        /// The pass index to use.
        #[arg(short, long)]
        index: usize,

        #[arg(value_enum, short, long, default_value = "cross")]
        backend: ReflectionBackend,
    },
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum PreprocessOutput {
    #[clap(name = "fragment")]
    Fragment,
    #[clap(name = "vertex")]
    Vertex,
    #[clap(name = "params")]
    Params,
    #[clap(name = "passformat")]
    Format,
    #[clap(name = "json")]
    Json,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum TranspileStage {
    #[clap(name = "fragment")]
    Fragment,
    #[clap(name = "vertex")]
    Vertex,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum TranspileFormat {
    #[clap(name = "glsl")]
    GLSL,
    #[clap(name = "hlsl")]
    HLSL,
    #[clap(name = "wgsl")]
    WGSL,
    #[clap(name = "msl")]
    MSL,
    #[clap(name = "spirv")]
    SPIRV,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum PackFormat {
    #[clap(name = "json")]
    JSON,
    #[clap(name = "msgpack")]
    MsgPack,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum PackShaderLanguage {
    #[clap(name = "glsl")]
    GLSL,
    #[clap(name = "wgsl")]
    WGSL,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum Runtime {
    #[cfg(feature = "opengl")]
    #[clap(name = "opengl3")]
    OpenGL3,
    #[cfg(feature = "opengl")]
    #[clap(name = "opengl4")]
    OpenGL4,
    #[cfg(feature = "vulkan")]
    #[clap(name = "vulkan")]
    Vulkan,
    #[cfg(feature = "wgpu")]
    #[clap(name = "wgpu")]
    Wgpu,
    #[cfg(all(windows, feature = "d3d9"))]
    #[clap(name = "d3d9")]
    Direct3D9,
    #[cfg(all(windows, feature = "d3d11"))]
    #[clap(name = "d3d11")]
    Direct3D11,
    #[cfg(all(windows, feature = "d3d12"))]
    #[clap(name = "d3d12")]
    Direct3D12,
    #[cfg(all(target_vendor = "apple", feature = "metal"))]
    #[clap(name = "metal")]
    Metal,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum ShaderDefinesEnums {
    #[clap(name = "originalaspect-uniforms")]
    OriginalAspectUniforms,
    #[clap(name = "frametime-uniforms")]
    FrametimeUniforms,
}

#[derive(clap::ValueEnum, Clone, Debug)]
enum ReflectionBackend {
    #[clap(name = "cross")]
    SpirvCross,
    #[clap(name = "naga")]
    Naga,
}

macro_rules! get_runtime {
    ($rt:ident, $image:ident) => {
        match $rt {
            #[cfg(feature = "opengl")]
            Runtime::OpenGL3 => &mut librashader_test::render::gl::OpenGl3::new($image.as_path())?,
            #[cfg(feature = "opengl")]
            Runtime::OpenGL4 => &mut librashader_test::render::gl::OpenGl4::new($image.as_path())?,
            #[cfg(feature = "vulkan")]
            Runtime::Vulkan => &mut librashader_test::render::vk::Vulkan::new($image.as_path())?,
            #[cfg(feature = "wgpu")]
            Runtime::Wgpu => &mut librashader_test::render::wgpu::Wgpu::new($image.as_path())?,
            #[cfg(all(windows, feature = "d3d9"))]
            Runtime::Direct3D9 => {
                &mut librashader_test::render::d3d9::Direct3D9::new($image.as_path())?
            }
            #[cfg(all(windows, feature = "d3d11"))]
            Runtime::Direct3D11 => {
                &mut librashader_test::render::d3d11::Direct3D11::new($image.as_path())?
            }
            #[cfg(all(windows, feature = "d3d12"))]
            Runtime::Direct3D12 => {
                &mut librashader_test::render::d3d12::Direct3D12::new($image.as_path())?
            }
            #[cfg(all(target_vendor = "apple", feature = "metal"))]
            Runtime::Metal => &mut librashader_test::render::mtl::Metal::new($image.as_path())?,
        }
    };
}
pub fn main() -> Result<(), anyhow::Error> {
    let args = Args::parse();

    match args.command {
        Commands::Render {
            preset,
            render,
            out,
            runtime,
        } => {
            let PresetArgs { preset, wildcards } = preset;
            let RenderArgs {
                frame,
                dimensions,
                params,
                passes_enabled,
                image,
                options,
            } = render;

            let test: &mut dyn RenderTest = get_runtime!(runtime, image);
            let dimensions = parse_dimension(dimensions, test.image_size())?;

            let mut features = ShaderFeatures::NONE;
            if options
                .as_ref()
                .is_some_and(|args| args.aspect_ratio.is_some())
            {
                features |= ShaderFeatures::ORIGINAL_ASPECT_UNIFORMS;
            }

            if options
                .as_ref()
                .is_some_and(|args| args.frames_per_second.is_some())
                || options
                    .as_ref()
                    .is_some_and(|args| args.frametime_delta.is_some())
            {
                features |= ShaderFeatures::FRAMETIME_UNIFORMS;
            }

            if options.as_ref().is_some_and(|args| {
                args.gyroscope.is_some()
                    || args.accelerometer.is_some()
                    || args.accelerometer_rest.is_some()
            }) {
                features |= ShaderFeatures::SENSOR_UNIFORMS;
            }

            let preset = get_shader_preset(preset, wildcards, features)?;
            let params = parse_params(params)?;

            let image = test.render_with_preset_and_params(
                preset,
                frame,
                Some(dimensions),
                Some(&|rp| set_params(rp, &params, passes_enabled)),
                options.map(CommonFrameOptions::from),
            )?;

            if out.as_path() == Path::new("-") {
                let out = std::io::stdout();
                image.write_with_encoder(PngEncoder::new(out))?;
            } else {
                image.save(out)?;
            }
        }
        Commands::Compare {
            preset,
            render,
            left,
            right,
            out,
        } => {
            let PresetArgs { preset, wildcards } = preset;
            let RenderArgs {
                frame,
                dimensions,
                params,
                passes_enabled,
                image,
                options,
            } = render;

            let left: &mut dyn RenderTest = get_runtime!(left, image);
            let right: &mut dyn RenderTest = get_runtime!(right, image);

            let mut features = ShaderFeatures::NONE;
            if options
                .as_ref()
                .is_some_and(|args| args.aspect_ratio.is_some())
            {
                features |= ShaderFeatures::ORIGINAL_ASPECT_UNIFORMS;
            }

            if options
                .as_ref()
                .is_some_and(|args| args.frames_per_second.is_some())
                || options
                    .as_ref()
                    .is_some_and(|args| args.frametime_delta.is_some())
            {
                features |= ShaderFeatures::FRAMETIME_UNIFORMS;
            }

            if options.as_ref().is_some_and(|args| {
                args.gyroscope.is_some()
                    || args.accelerometer.is_some()
                    || args.accelerometer_rest.is_some()
            }) {
                features |= ShaderFeatures::SENSOR_UNIFORMS;
            }

            let dimensions = parse_dimension(dimensions, left.image_size())?;
            let params = parse_params(params)?;

            let left_preset = get_shader_preset(preset.clone(), wildcards.clone(), features)?;
            let left_image = left.render_with_preset_and_params(
                left_preset,
                frame,
                Some(dimensions),
                Some(&|rp| set_params(rp, &params, passes_enabled)),
                None,
            )?;

            let right_preset = get_shader_preset(preset.clone(), wildcards.clone(), features)?;
            let right_image = right.render_with_preset_and_params(
                right_preset,
                frame,
                Some(dimensions),
                Some(&|rp| set_params(rp, &params, passes_enabled)),
                options.map(CommonFrameOptions::from),
            )?;

            let similarity = image_compare::rgba_hybrid_compare(&left_image, &right_image)?;
            print!("{}", similarity.score);

            if let Some(out) = out {
                let image = similarity.image.to_color_map();
                if out.as_path() == Path::new("-") {
                    let out = std::io::stdout();
                    image.write_with_encoder(PngEncoder::new(out))?;
                } else {
                    image.save(out)?;
                }
            }
        }
        Commands::Parse { preset, flags } => {
            let PresetArgs { preset, wildcards } = preset;

            let preset = get_shader_preset(preset, wildcards, flags.into())?;
            let out = serde_json::to_string_pretty(&preset)?;
            print!("{out:}");
        }
        Commands::Preprocess {
            shader,
            output,
            flags,
        } => {
            let source =
                librashader::preprocess::ShaderSource::load(shader.as_path(), flags.into())?;
            match output {
                PreprocessOutput::Fragment => print!("{}", source.fragment),
                PreprocessOutput::Vertex => print!("{}", source.vertex),
                PreprocessOutput::Params => {
                    print!("{}", serde_json::to_string_pretty(&source.parameters)?)
                }
                PreprocessOutput::Format => print!("{:?}", source.format),
                PreprocessOutput::Json => print!("{}", serde_json::to_string_pretty(&source)?),
            }
        }
        Commands::Transpile {
            shader,
            stage,
            format,
            version,
            flags,
        } => {
            let source =
                librashader::preprocess::ShaderSource::load(shader.as_path(), flags.into())?;
            let compilation = SpirvCompilation::try_from(&source)?;
            let output = match format {
                TranspileFormat::GLSL => {
                    let mut compilation =
                        librashader::reflect::targets::GLSL::from_compilation(compilation)?;
                    compilation.validate()?;

                    let version = version
                        .map(|s| parse_glsl_version(&s))
                        .unwrap_or(Ok(GlslVersion::Glsl330))?;

                    let output = compilation.compile(version)?;
                    TranspileOutput {
                        vertex: output.vertex,
                        fragment: output.fragment,
                    }
                }
                TranspileFormat::HLSL => {
                    let mut compilation =
                        librashader::reflect::targets::HLSL::from_compilation(compilation)?;
                    compilation.validate()?;

                    let shader_model = version
                        .map(|s| parse_hlsl_version(&s))
                        .unwrap_or(Ok(HlslShaderModel::ShaderModel5_0))?;

                    let output = compilation.compile(Some(shader_model))?;
                    TranspileOutput {
                        vertex: output.vertex,
                        fragment: output.fragment,
                    }
                }
                TranspileFormat::WGSL => {
                    let mut compilation =
                        librashader::reflect::targets::WGSL::from_compilation(compilation)?;
                    compilation.validate()?;
                    let output = compilation.compile(NagaLoweringOptions {
                        write_pcb_as_ubo: true,
                        sampler_bind_group: 1,
                        suppress_derivative_uniformity: false,
                    })?;
                    TranspileOutput {
                        vertex: output.vertex,
                        fragment: output.fragment,
                    }
                }
                TranspileFormat::MSL => {
                    let mut compilation =
                        <librashader::reflect::targets::MSL as FromCompilation<
                            SpirvCompilation,
                            SpirvCross,
                        >>::from_compilation(compilation)?;
                    compilation.validate()?;

                    let version = version
                        .map(|s| parse_msl_version(&s))
                        .unwrap_or(Ok(MslVersion::new(1, 2, 0)))?;

                    let output = compilation.compile(Some(version))?;

                    TranspileOutput {
                        vertex: output.vertex,
                        fragment: output.fragment,
                    }
                }
                TranspileFormat::SPIRV => {
                    let mut compilation =
                        <librashader::reflect::targets::SPIRV as FromCompilation<
                            SpirvCompilation,
                            SpirvCross,
                        >>::from_compilation(compilation)?;
                    compilation.validate()?;
                    let output = compilation.compile(None)?;

                    let raw = version.is_some_and(|s| s == "raw-id");
                    TranspileOutput {
                        vertex: spirv_to_dis(output.vertex, raw)?,
                        fragment: spirv_to_dis(output.fragment, raw)?,
                    }
                }
            };

            let print = match stage {
                TranspileStage::Fragment => output.fragment,
                TranspileStage::Vertex => output.vertex,
            };

            print!("{print}")
        }
        Commands::Reflect {
            preset,
            flags,
            index,
            backend,
        } => {
            let PresetArgs { preset, wildcards } = preset;

            let preset = get_shader_preset(preset, wildcards, flags.into())?;
            let Some(shader) = preset.passes.get(index) else {
                return Err(anyhow!("Invalid pass index for the preset"));
            };

            let source = librashader::preprocess::ShaderSource::load(
                shader.path.as_path(),
                preset.features,
            )?;
            let compilation = SpirvCompilation::try_from(&source)?;

            let semantics =
                ShaderSemantics::create_pass_semantics::<anyhow::Error>(&preset, index)?;

            let reflection = match backend {
                ReflectionBackend::SpirvCross => {
                    let mut compilation =
                        <librashader::reflect::targets::SPIRV as FromCompilation<
                            SpirvCompilation,
                            SpirvCross,
                        >>::from_compilation(compilation)?;
                    compilation.reflect(index, &semantics)?
                }
                ReflectionBackend::Naga => {
                    let mut compilation =
                        <librashader::reflect::targets::SPIRV as FromCompilation<
                            SpirvCompilation,
                            Naga,
                        >>::from_compilation(compilation)?;
                    compilation.reflect(index, &semantics)?
                }
            };

            print!("{}", serde_json::to_string_pretty(&reflection)?);
        }
        Commands::Pack {
            preset,
            flags,
            out,
            format,
            language,
        } => {
            let PresetArgs { preset, wildcards } = preset;
            let preset = get_shader_preset(preset, wildcards, flags.into())?;
            let mut preset = ShaderPresetPack::load_from_preset::<anyhow::Error>(preset)?;

            if matches!(language, PackShaderLanguage::WGSL) {
                for pass in preset.passes.iter_mut() {
                    let compilation = SpirvCompilation::try_from(&pass.data)?;
                    let mut wgsl =
                        librashader::reflect::targets::WGSL::from_compilation(compilation)?;
                    wgsl.validate()?;
                    let output = wgsl.compile(NagaLoweringOptions {
                        // Don't lower PCBs at this point yet or it will fail validation.
                        // When we re-load it, librashader will revalidate and do the WGSL-side lowering
                        // after validation.
                        write_pcb_as_ubo: false,
                        sampler_bind_group: 1,
                        suppress_derivative_uniformity: false,
                    })?;
                    pass.data.vertex = output.vertex;
                    pass.data.fragment = output.fragment;
                }
                preset.language = librashader::presets::ShaderSourceLanguage::Wgsl;
            }

            let output_bytes = match format {
                PackFormat::JSON => serde_json::to_vec_pretty(&preset)?,
                PackFormat::MsgPack => rmp_serde::to_vec(&preset)?,
            };

            if out.as_path() == Path::new("-") {
                let mut out = std::io::stdout();
                out.write_all(output_bytes.as_slice())?;
            } else {
                let mut file = File::create(out.as_path())?;
                file.write_all(output_bytes.as_slice())?;
            }
        }
    }

    Ok(())
}

struct TranspileOutput {
    vertex: String,
    fragment: String,
}

fn get_shader_preset(
    preset: PathBuf,
    wildcards: Option<Vec<String>>,
    flags: ShaderFeatures,
) -> anyhow::Result<ShaderPreset> {
    let mut context = WildcardContext::new();
    context.add_path_defaults(preset.as_path());
    if let Some(wildcards) = wildcards {
        for string in wildcards {
            let Some((left, right)) = string.split_once("=") else {
                return Err(anyhow!("Encountered invalid context string {string}"));
            };

            context.append_item(ContextItem::ExternContext(
                left.to_string(),
                right.to_string(),
            ))
        }
    }
    let preset = ShaderPreset::try_parse_with_context(preset, flags, context)?;
    Ok(preset)
}

fn parse_params(
    assignments: Option<Vec<String>>,
) -> anyhow::Result<Option<FastHashMap<ShortString, f32>>> {
    let Some(assignments) = assignments else {
        return Ok(None);
    };

    let mut map = FastHashMap::default();
    for string in assignments {
        let Some((left, right)) = string.split_once("=") else {
            return Err(anyhow!("Encountered invalid parameter string {string}"));
        };

        let value = right
            .parse::<f32>()
            .map_err(|_| anyhow!("Encountered invalid parameter value: {right}"))?;

        map.insert(ShortString::from(left), value);
    }

    Ok(Some(map))
}

fn set_params(
    params: &RuntimeParameters,
    assignments: &Option<FastHashMap<ShortString, f32>>,
    passes_enabled: Option<usize>,
) {
    if let Some(passes_enabled) = passes_enabled {
        params.set_passes_enabled(passes_enabled)
    };

    let Some(assignments) = assignments else {
        return;
    };

    params.update_parameters(|params| {
        for (key, param) in assignments {
            params.insert(key.clone(), *param);
        }
    });
}

fn spirv_to_dis(spirv: Vec<u32>, raw: bool) -> anyhow::Result<String> {
    let binary = spq_spvasm::SpirvBinary::from(spirv);
    spq_spvasm::Disassembler::new()
        .print_header(true)
        .name_ids(!raw)
        .name_type_ids(!raw)
        .name_const_ids(!raw)
        .indent(true)
        .disassemble(&binary)
}

fn parse_glsl_version(version_str: &str) -> anyhow::Result<GlslVersion> {
    if version_str.contains("es") {
        let Some(version) = version_str.strip_suffix("es").map(|s| s.trim()) else {
            return Err(anyhow!("Unknown GLSL version"));
        };

        Ok(match version {
            "100" => GlslVersion::Glsl100Es,
            "300" => GlslVersion::Glsl300Es,
            "310" => GlslVersion::Glsl310Es,
            "320" => GlslVersion::Glsl320Es,
            _ => return Err(anyhow!("Unknown GLSL version")),
        })
    } else {
        Ok(match version_str {
            "100" => GlslVersion::Glsl100Es,
            "110" => GlslVersion::Glsl110,
            "120" => GlslVersion::Glsl120,
            "130" => GlslVersion::Glsl130,
            "140" => GlslVersion::Glsl140,
            "150" => GlslVersion::Glsl150,
            "300" => GlslVersion::Glsl300Es,
            "330" => GlslVersion::Glsl330,
            "310" => GlslVersion::Glsl310Es,
            "320" => GlslVersion::Glsl320Es,
            "400" => GlslVersion::Glsl400,
            "410" => GlslVersion::Glsl410,
            "420" => GlslVersion::Glsl420,
            "430" => GlslVersion::Glsl430,
            "440" => GlslVersion::Glsl440,
            "450" => GlslVersion::Glsl450,
            "460" => GlslVersion::Glsl460,
            _ => return Err(anyhow!("Unknown GLSL version")),
        })
    }
}

fn version_to_usize(version_str: &str) -> anyhow::Result<usize> {
    let version: &str = if version_str.contains("_") {
        &version_str.replace("_", "")
    } else if version_str.contains(".") {
        &version_str.replace(".", "")
    } else {
        version_str
    };

    let version = version
        .parse::<usize>()
        .map_err(|_| anyhow!("Invalid version string"))?;
    Ok(version)
}

fn parse_hlsl_version(version_str: &str) -> anyhow::Result<HlslShaderModel> {
    let version = version_to_usize(version_str)?;
    Ok(match version {
        30 => HlslShaderModel::ShaderModel3_0,
        40 => HlslShaderModel::ShaderModel4_0,
        50 => HlslShaderModel::ShaderModel5_0,
        51 => HlslShaderModel::ShaderModel5_1,
        60 => HlslShaderModel::ShaderModel6_0,
        61 => HlslShaderModel::ShaderModel6_1,
        62 => HlslShaderModel::ShaderModel6_2,
        63 => HlslShaderModel::ShaderModel6_3,
        64 => HlslShaderModel::ShaderModel6_4,
        65 => HlslShaderModel::ShaderModel6_5,
        66 => HlslShaderModel::ShaderModel6_6,
        67 => HlslShaderModel::ShaderModel6_7,
        68 => HlslShaderModel::ShaderModel6_8,
        _ => return Err(anyhow!("Unknown Shader Model")),
    })
}

fn parse_msl_version(version_str: &str) -> anyhow::Result<MslVersion> {
    let version = version_to_usize(version_str)?;
    Ok(match version {
        10 => MslVersion::new(1, 0, 0),
        11 => MslVersion::new(1, 1, 0),
        12 => MslVersion::new(1, 2, 0),
        20 => MslVersion::new(2, 0, 0),
        21 => MslVersion::new(2, 1, 0),
        22 => MslVersion::new(2, 2, 0),
        23 => MslVersion::new(2, 3, 0),
        24 => MslVersion::new(2, 4, 0),
        30 => MslVersion::new(3, 0, 0),
        31 => MslVersion::new(3, 1, 0),
        32 => MslVersion::new(3, 2, 0),
        n if n >= 10000 => {
            let major = n / 10000;
            let minor = (n - (major * 10000)) / 100;
            let patch = n - ((major * 10000) + (minor * 100));
            MslVersion::new(major as u32, minor as u32, patch as u32)
        }
        _ => return Err(anyhow!("Unknown MSL version")),
    })
}

fn parse_dimension(dimstr: Option<String>, image_dim: Size<u32>) -> anyhow::Result<Size<u32>> {
    let Some(dimstr) = dimstr else {
        return Ok(image_dim);
    };

    if dimstr.contains("x") {
        if let Some((Ok(width), Ok(height))) = dimstr
            .split_once("x")
            .map(|(width, height)| (width.parse::<u32>(), height.parse::<u32>()))
        {
            if width < 1 || height < 1 {
                return Err(anyhow!("Dimensions must be larger than 1x1"));
            }

            if width > 16384 || height > 16384 {
                return Err(anyhow!("Dimensions must not be larger than 16384x16384"));
            }
            return Ok(Size::new(width, height));
        }
    }

    if dimstr.ends_with("%") && dimstr.len() > 1 {
        if let Ok(percent) = dimstr.trim_end_matches("%").parse::<u32>() {
            let percent = percent as f32 / 100f32;
            let width = (image_dim.width as f32 * percent) as u32;
            let height = (image_dim.height as f32 * percent) as u32;

            if width < 1 || height < 1 {
                return Err(anyhow!("Dimensions must be larger than 1x1"));
            }

            if width > 16384 || height > 16384 {
                return Err(anyhow!("Dimensions must not be larger than 16384x16384"));
            }

            return Ok(Size { width, height });
        }
    }

    Err(anyhow!(
        "Invalid dimension syntax, must either in form WIDTHxHEIGHT or SCALE%"
    ))
}