shadertoy-cli 2.2.7

Agent-friendly ShaderToy project, rendering, debugging, and live-preview CLI
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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
mod conversions;
use crate::docs;
use crate::ops;
use crate::ops::{
    BlindCreateOptions, BlindJudgeOptions, BlindRevealOptions, ChannelSetOptions,
    InspectBufferOptions, InspectMode, InspectStorageOptions, InspectStorageType,
    InspectVisualization, Output, ProfileOptions, RenderAudioOptions, RenderFramesOptions,
    RenderOptions, RenderVideoOptions, ReplayOptions, SweepOptions, TestOptions,
};
use crate::preview;
use crate::preview::PreviewConfig;
use anyhow::Result;
use clap::{Args, Parser, Subcommand, ValueEnum};
use serde_json::json;
use std::path::PathBuf;
use std::process::ExitCode;

#[derive(Debug, Parser)]
#[command(
    name = "shadertoy",
    version,
    about = "Agent-friendly ShaderToy project, rendering, inspection, and live-preview CLI"
)]
struct Cli {
    /// Emit machine-readable JSON results and errors on stdout.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create a new ShaderToy project directory.
    New(NewArgs),
    /// Initialize the current/existing directory as a ShaderToy project.
    Init(InitArgs),
    /// Import a ShaderToy URL or shader id through Camoufox into a local project.
    Import(ImportArgs),
    /// Validate the manifest, graph, assets, and GLSL compilation.
    Check(ProjectPathArgs),
    /// Build the project into an STTF artifact.
    Build(BuildArgs),
    /// Deterministically render the final image or a named 2D buffer/compute pass.
    Render(RenderArgs),
    /// Render multiple deterministic frames in one runtime, optionally as a contact sheet.
    RenderFrames(RenderFramesArgs),
    /// Encode a deterministic animation through ffmpeg.
    RenderVideo(RenderVideoArgs),
    /// Render a ShaderToy Sound pass to deterministic stereo PCM WAV.
    RenderAudio(RenderAudioArgs),
    /// Measure isolated per-pass GPU timings and profiled CPU render-call cost.
    Profile(ProfileArgs),
    /// Render a Cartesian product of custom-uniform values for visual comparison.
    Sweep(SweepArgs),
    /// Create, judge, and reveal blinded visual comparisons.
    Blind(BlindArgs),
    /// Run deterministic visual and numeric regression tests from [[test]] cases.
    Test(TestArgs),
    /// Reproduce a recorded preview-input timeline.
    Replay(ReplayArgs),
    /// Run a native-rendered live preview web server with hot reload.
    Preview(PreviewArgs),
    /// Inspect project structure progressively, from summary to pass/channel detail.
    Inspect(InspectArgs),
    /// Capture, inspect, or modify resumable feedback-buffer state.
    State(StateArgs),
    /// Safely mutate shader passes in ShaderToy.toml.
    Pass(PassArgs),
    /// Safely mutate iChannel bindings in ShaderToy.toml.
    Channel(ChannelArgs),
    /// Read concise built-in project/agent documentation.
    Docs(DocsArgs),
}

#[derive(Debug, Args)]
struct NewArgs {
    /// Destination directory. Its basename becomes project.name.
    path: PathBuf,
    #[arg(long, value_enum, default_value_t = TemplateArg::Minimal)]
    template: TemplateArg,
}

#[derive(Debug, Args)]
struct InitArgs {
    #[arg(default_value = ".")]
    path: PathBuf,
    #[arg(long, value_enum, default_value_t = TemplateArg::Minimal)]
    template: TemplateArg,
}

#[derive(Debug, Args)]
struct ImportArgs {
    /// ShaderToy view URL or shader id.
    source: String,
    /// Destination directory. Defaults to a filesystem-safe form of the shader name.
    #[arg(short, long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct ProjectPathArgs {
    /// Project directory (or any path inside it).
    #[arg(value_name = "PATH", conflicts_with = "project")]
    path: Option<PathBuf>,
    /// Project directory (or any path inside it).
    #[arg(long, value_name = "PATH")]
    project: Option<PathBuf>,
}

impl ProjectPathArgs {
    fn resolved(&self) -> PathBuf {
        self.project
            .clone()
            .or_else(|| self.path.clone())
            .unwrap_or_else(|| PathBuf::from("."))
    }
}

#[derive(Debug, Args)]
struct BuildArgs {
    /// Project directory (or any path inside it).
    #[arg(value_name = "PATH", conflicts_with = "project")]
    path: Option<PathBuf>,
    /// Project directory (or any path inside it).
    #[arg(long, value_name = "PATH")]
    project: Option<PathBuf>,
    /// Output STTF path. Defaults to target/PROJECT.sttf.
    #[arg(short, long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct RenderArgs {
    /// Project directory (or any path inside it).
    #[arg(long, default_value = ".")]
    project: PathBuf,
    /// Output PNG path. Defaults to target/render.png.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Render/snapshot a named pass instead of the final Image pass.
    #[arg(long)]
    pass: Option<String>,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    /// Deterministic target iFrame.
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    /// Deterministic target iTime in seconds.
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Resume from a previously captured .ststate artifact.
    #[arg(long)]
    state: Option<PathBuf>,
    /// Override a persistent 2D pass immediately before the target frame, e.g. buffer-a=fixture.png.
    #[arg(long = "set-buffer")]
    set_buffers: Vec<String>,
    /// Override a declared custom uniform, e.g. --set wave_height=2.0.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct RenderFramesArgs {
    /// Project directory (or any path inside it).
    #[arg(long, default_value = ".")]
    project: PathBuf,
    /// Directory for individual PNG frames. Defaults to PROJECT/target/frames.
    #[arg(long)]
    output_dir: Option<PathBuf>,
    /// Also write a contact-sheet PNG containing the requested frames.
    #[arg(long)]
    contact_sheet: Option<PathBuf>,
    /// Contact-sheet column count. Defaults to a near-square layout.
    #[arg(long, requires = "contact_sheet")]
    columns: Option<u32>,
    /// Render/snapshot a named pass instead of the final Image pass.
    #[arg(long)]
    pass: Option<String>,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    /// Deterministic iFrames to render, e.g. --frames 0,60,120,180.
    #[arg(long, value_delimiter = ',', num_args = 1.., required_unless_present = "range", conflicts_with = "range")]
    frames: Vec<i32>,
    /// Inclusive START:END[:STEP] deterministic frame range.
    #[arg(long, required_unless_present = "frames", conflicts_with = "frames")]
    range: Option<String>,
    /// Override a declared custom uniform for every rendered frame.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct RenderAudioArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Sound pass name. Required only when the project has multiple Sound passes.
    #[arg(long)]
    pass: Option<String>,
    #[arg(long, default_value_t = 10.0)]
    duration: f32,
    #[arg(long, default_value_t = 44_100)]
    sample_rate: u32,
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct RenderVideoArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    /// Encoded output. Extension selects sensible defaults for mp4/webm/gif.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Render/snapshot a named pass instead of final Image.
    #[arg(long)]
    pass: Option<String>,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, default_value_t = 0)]
    start_frame: i32,
    /// Number of output frames.
    #[arg(long, conflicts_with = "duration")]
    frames: Option<u32>,
    /// Output duration in seconds. Defaults to 5 seconds when --frames is omitted.
    #[arg(long, conflicts_with = "frames")]
    duration: Option<f32>,
    /// Optional explicit ffmpeg video codec.
    #[arg(long)]
    codec: Option<String>,
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct ProfileArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Unmeasured frames rendered before sampling.
    #[arg(long, default_value_t = 3)]
    warmup: u32,
    /// Consecutive measured frames.
    #[arg(long, default_value_t = 20)]
    samples: u32,
    /// Override a declared custom uniform during profiling.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct SweepArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    /// Directory for variant PNGs. Defaults to PROJECT/target/sweep.
    #[arg(long)]
    output_dir: Option<PathBuf>,
    /// Contact-sheet path. Defaults to OUTPUT_DIR/contact-sheet.png.
    #[arg(long, conflicts_with = "no_contact_sheet")]
    contact_sheet: Option<PathBuf>,
    /// Skip contact-sheet generation.
    #[arg(long, conflicts_with = "blind")]
    no_contact_sheet: bool,
    /// Randomize/anonymize variants as A/B/C and seal the parameter mapping until judged.
    #[arg(long, conflicts_with = "no_contact_sheet")]
    blind: bool,
    /// Contact-sheet column count. Defaults to a near-square layout.
    #[arg(long)]
    columns: Option<u32>,
    /// Render/snapshot a named 2D buffer/compute pass instead of the final Image pass.
    #[arg(long)]
    pass: Option<String>,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Sweep a declared custom uniform. Scalars use commas; vectors use semicolons between vectors.
    #[arg(long = "set", value_name = "NAME=VALUES", required = true)]
    sweep_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct BlindArgs {
    #[command(subcommand)]
    command: BlindCommand,
}

#[derive(Debug, Subcommand)]
enum BlindCommand {
    /// Create a blinded comparison from images, render directories, ShaderToy projects, STTF builds, or git refs.
    Create(BlindCreateArgs),
    /// Commit a visual preference and reasoning while the source/parameter mapping remains sealed.
    Judge(BlindJudgeArgs),
    /// Reveal the source/parameter mapping after a judgment has been recorded.
    Reveal(BlindRevealArgs),
}

#[derive(Debug, Args)]
struct BlindCreateArgs {
    /// Sources to blind. Paths auto-detect images, image directories, ShaderToy projects, and .sttf builds. Use git:REF or git:REF::SUBDIR for git revisions.
    #[arg(required = true, num_args = 2..)]
    sources: Vec<String>,
    /// Output directory. Defaults to target/blind-comparison.
    #[arg(long)]
    output_dir: Option<PathBuf>,
    /// Deterministic frames for project/STTF sources.
    #[arg(long, value_delimiter = ',', default_value = "0")]
    frames: Vec<i32>,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    /// Git repository root for git:REF sources. Defaults to the containing repository.
    #[arg(long)]
    git_root: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct BlindJudgeArgs {
    /// blind-session.json path or its containing comparison directory.
    session: PathBuf,
    /// Anonymous variant label to select, e.g. A or B.
    #[arg(long)]
    pick: String,
    /// Reasoning for the preference. Stored before the mapping can be revealed.
    #[arg(
        long,
        required_unless_present = "reason_file",
        conflicts_with = "reason_file"
    )]
    reason: Option<String>,
    /// Read the reasoning from a UTF-8 text/Markdown file.
    #[arg(long, required_unless_present = "reason", conflicts_with = "reason")]
    reason_file: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct BlindRevealArgs {
    /// blind-session.json path or its containing comparison directory.
    session: PathBuf,
}

#[derive(Debug, Args)]
struct ReplayArgs {
    /// .strec recording produced by preview --record.
    recording: PathBuf,
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[arg(short, long)]
    output: Option<PathBuf>,
    #[arg(long)]
    pass: Option<String>,
    /// Recorded timeline frame. Defaults to the final captured frame.
    #[arg(long)]
    frame: Option<u64>,
    /// Replay despite a source/manifest/asset fingerprint mismatch.
    #[arg(long)]
    allow_project_changes: bool,
}

#[derive(Debug, Args)]
struct TestArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    /// Rewrite visual reference images from the current deterministic render.
    #[arg(long)]
    update: bool,
    /// Run only test names containing this substring.
    #[arg(long)]
    filter: Option<String>,
}

#[derive(Debug, Args)]
struct PreviewArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[arg(long, default_value = "127.0.0.1")]
    host: String,
    #[arg(long, default_value_t = 4321)]
    port: u16,
    /// Force opening the browser.
    #[arg(long)]
    open: bool,
    /// Never open the browser automatically.
    #[arg(long)]
    no_open: bool,
    /// Required when binding preview to a non-loopback address.
    #[arg(long)]
    token: Option<String>,
    /// Reset time/buffer state on every successful hot reload.
    #[arg(long)]
    reset_on_reload: bool,
    /// Record shader-affecting preview input and exact rendered frame/time markers.
    #[arg(long, value_name = "PATH")]
    record: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct InspectArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[command(subcommand)]
    command: Option<InspectCommand>,
}

#[derive(Debug, Subcommand)]
enum InspectCommand {
    /// Show the complete pass/channel dependency graph.
    Graph,
    /// Inspect one pass.
    Pass { name: String },
    /// Inspect one pass's iChannel bindings.
    Channels { name: String },
    /// Render and inspect a 2D buffer/compute pass's floating-point contents.
    Buffer(InspectBufferArgs),
    /// Render and inspect a named shader-storage buffer.
    Storage(InspectStorageArgs),
    /// Inspect a .ststate artifact.
    State { path: PathBuf },
}

#[derive(Debug, Args)]
struct InspectBufferArgs {
    name: String,
    /// Render-target index for MRT passes (0 is the primary output).
    #[arg(long, default_value_t = 0)]
    output_index: u8,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Shader-coordinate pixel (x,y) to print.
    #[arg(long, value_parser = parse_pixel)]
    pixel: Option<(u32, u32)>,
    /// Optional diagnostic PNG.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Optional little-endian raw RGBA32F dump.
    #[arg(long)]
    raw: Option<PathBuf>,
    /// Diagnostic PNG mapping: auto, rgb, signed, or magnitude.
    ///
    /// auto uses rgb for values inside 0..1 and signed otherwise; signed centers
    /// zero at 0.5 using the largest absolute RGB value; magnitude writes
    /// normalized vector length as grayscale.
    #[arg(long, value_enum, default_value_t = InspectVisualizationArg::Auto)]
    visualization: InspectVisualizationArg,
    /// Override a declared custom uniform during inspection.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct InspectStorageArgs {
    name: String,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Byte offset into the SSBO.
    #[arg(long, default_value_t = 0)]
    offset: usize,
    /// Number of typed values to print.
    #[arg(long, default_value_t = 16)]
    count: usize,
    #[arg(long = "type", value_enum, default_value_t = InspectStorageTypeArg::F32)]
    value_type: InspectStorageTypeArg,
    /// Optional complete raw SSBO dump.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Override a declared custom uniform during inspection.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct StateArgs {
    #[command(subcommand)]
    command: StateCommand,
}

#[derive(Debug, Subcommand)]
enum StateCommand {
    /// Render deterministically to a point and capture lossless persistent buffer state.
    Capture(StateCaptureArgs),
    /// Inspect .ststate metadata without loading OpenGL.
    Inspect { path: PathBuf },
    /// Replace one or more buffers inside an existing state using exact-size images.
    Set(StateSetArgs),
    /// Replace one or more captured SSBOs using exact-size binary files.
    SetStorage(StateSetStorageArgs),
}

#[derive(Debug, Args)]
struct StateCaptureArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[arg(short, long)]
    output: PathBuf,
    #[arg(long)]
    width: Option<u32>,
    #[arg(long)]
    height: Option<u32>,
    #[arg(long)]
    fps: Option<f32>,
    #[arg(long, conflicts_with = "time")]
    frame: Option<i32>,
    #[arg(long, conflicts_with = "frame")]
    time: Option<f32>,
    /// Include named shader-storage buffers in the resumable state.
    #[arg(long)]
    include_storage: bool,
    /// Override a declared custom uniform while producing the captured state.
    #[arg(long = "set", value_name = "NAME=VALUE")]
    set_uniforms: Vec<String>,
}

#[derive(Debug, Args)]
struct StateSetArgs {
    input: PathBuf,
    /// BUFFER=IMAGE assignments.
    #[arg(required = true)]
    assignments: Vec<String>,
    #[arg(short, long)]
    output: PathBuf,
}

#[derive(Debug, Args)]
struct StateSetStorageArgs {
    input: PathBuf,
    /// STORAGE=BINARY assignments.
    #[arg(required = true)]
    assignments: Vec<String>,
    #[arg(short, long)]
    output: PathBuf,
}

#[derive(Debug, Args)]
struct PassArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[command(subcommand)]
    command: PassCommand,
}

#[derive(Debug, Subcommand)]
enum PassCommand {
    /// Add an offscreen buffer/cubemap/compute pass and create a source stub if needed.
    Add {
        name: String,
        #[arg(long, value_enum, default_value_t = PassKindArg::Buffer)]
        kind: PassKindArg,
        /// Source path relative to the project root.
        #[arg(long)]
        source: Option<PathBuf>,
    },
    /// Remove a non-final pass. Source files are intentionally left on disk.
    Remove {
        name: String,
        /// Also remove channel bindings that consume this pass.
        #[arg(long)]
        force: bool,
    },
}

#[derive(Debug, Args)]
struct ChannelArgs {
    #[arg(long, default_value = ".")]
    project: PathBuf,
    #[command(subcommand)]
    command: ChannelCommand,
}

#[derive(Debug, Subcommand)]
enum ChannelCommand {
    /// Set/replace one iChannel binding.
    Set {
        pass: String,
        /// iChannel index, 0..3.
        channel: u8,
        source: String,
        #[arg(long, value_enum)]
        kind: Option<InputKindArg>,
        /// Render-target index when the source is a multi-output pass.
        #[arg(long, default_value_t = 0)]
        output: u8,
        #[arg(long)]
        previous: bool,
        #[arg(long, value_enum, default_value_t = FilterArg::Linear)]
        filter: FilterArg,
        #[arg(long, value_enum, default_value_t = WrapArg::Repeat)]
        wrap: WrapArg,
    },
    /// Remove one iChannel binding.
    Remove {
        pass: String,
        /// iChannel index, 0..3.
        channel: u8,
    },
}

#[derive(Debug, Args)]
struct DocsArgs {
    /// agent, project, import, manifest, passes, glsl, assets, buffers, channels, state, sweep, blind, or preview.
    #[arg(default_value = "agent")]
    topic: String,
    /// Print the exact JSON Schema for ShaderToy.toml (manifest topic only).
    #[arg(long)]
    schema: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum InspectVisualizationArg {
    #[default]
    Auto,
    Rgb,
    Signed,
    Magnitude,
}

impl From<InspectVisualizationArg> for InspectVisualization {
    fn from(value: InspectVisualizationArg) -> Self {
        match value {
            InspectVisualizationArg::Auto => Self::Auto,
            InspectVisualizationArg::Rgb => Self::Rgb,
            InspectVisualizationArg::Signed => Self::Signed,
            InspectVisualizationArg::Magnitude => Self::Magnitude,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum InspectStorageTypeArg {
    Bytes,
    U32,
    I32,
    #[default]
    F32,
}

impl From<InspectStorageTypeArg> for InspectStorageType {
    fn from(value: InspectStorageTypeArg) -> Self {
        match value {
            InspectStorageTypeArg::Bytes => Self::Bytes,
            InspectStorageTypeArg::U32 => Self::U32,
            InspectStorageTypeArg::I32 => Self::I32,
            InspectStorageTypeArg::F32 => Self::F32,
        }
    }
}

fn parse_pixel(value: &str) -> std::result::Result<(u32, u32), String> {
    let (x, y) = value
        .split_once(',')
        .ok_or_else(|| "pixel must be formatted as X,Y".to_string())?;
    let x = x
        .parse::<u32>()
        .map_err(|_| "pixel X must be an unsigned integer".to_string())?;
    let y = y
        .parse::<u32>()
        .map_err(|_| "pixel Y must be an unsigned integer".to_string())?;
    Ok((x, y))
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum TemplateArg {
    #[default]
    Minimal,
    Multipass,
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum PassKindArg {
    #[default]
    Buffer,
    Cubemap,
    Compute,
    Sound,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum InputKindArg {
    Pass,
    Texture,
    Keyboard,
    Music,
    Video,
    Webcam,
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum FilterArg {
    Mipmap,
    #[default]
    Linear,
    Nearest,
}

#[derive(Debug, Clone, Copy, ValueEnum, Default)]
enum WrapArg {
    Clamp,
    #[default]
    Repeat,
}

pub fn run() -> ExitCode {
    let args = std::env::args_os().collect::<Vec<_>>();
    let json_requested = args.iter().skip(1).any(|arg| arg == "--json");
    let cli = match Cli::try_parse_from(args) {
        Ok(cli) => cli,
        Err(error) => {
            let exit_code = if error.use_stderr() { 2 } else { 0 };
            if json_requested && error.use_stderr() {
                println!(
                    "{}",
                    serde_json::to_string(&json!({
                        "ok": false,
                        "error": error.to_string(),
                        "kind": format!("{:?}", error.kind()),
                    }))
                    .expect("clap error JSON serialization cannot fail")
                );
            } else {
                let _ = error.print();
            }
            return ExitCode::from(exit_code);
        }
    };
    let json_mode = cli.json;

    let result = dispatch(cli.command, json_mode);
    match result {
        Ok(Some(output)) => {
            let success = output
                .json
                .get("ok")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(true);
            emit(output, json_mode);
            if success {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        Ok(None) => ExitCode::SUCCESS,
        Err(error) => {
            if json_mode {
                println!(
                    "{}",
                    serde_json::to_string(&json!({
                        "ok": false,
                        "error": format!("{error:#}"),
                    }))
                    .expect("error JSON serialization cannot fail")
                );
            } else {
                eprintln!("error: {error:#}");
            }
            ExitCode::from(1)
        }
    }
}

fn dispatch(command: Command, json_mode: bool) -> Result<Option<Output>> {
    let output = match command {
        Command::New(args) => ops::new_project(&args.path, args.template.into())?,
        Command::Init(args) => ops::init_project(&args.path, args.template.into())?,
        Command::Import(args) => ops::import_project(&args.source, args.output.as_deref())?,
        Command::Check(args) => ops::check_project(&args.resolved())?,
        Command::Build(args) => {
            let project = args
                .project
                .clone()
                .or_else(|| args.path.clone())
                .unwrap_or_else(|| PathBuf::from("."));
            ops::build_project(&project, args.output.as_deref())?
        }
        Command::Render(args) => ops::render_project(&RenderOptions {
            project: args.project,
            output: args.output,
            pass: args.pass,
            width: args.width,
            height: args.height,
            fps: args.fps,
            frame: args.frame,
            time: args.time,
            state: args.state,
            set_buffers: args.set_buffers,
            set_uniforms: args.set_uniforms,
        })?,
        Command::RenderFrames(args) => ops::render_frames_project(&RenderFramesOptions {
            project: args.project,
            output_dir: args.output_dir,
            contact_sheet: args.contact_sheet,
            columns: args.columns,
            pass: args.pass,
            width: args.width,
            height: args.height,
            fps: args.fps,
            frames: args.frames,
            range: args.range,
            set_uniforms: args.set_uniforms,
        })?,
        Command::RenderAudio(args) => ops::render_audio_project(&RenderAudioOptions {
            project: args.project,
            output: args.output,
            pass: args.pass,
            duration: args.duration,
            sample_rate: args.sample_rate,
            set_uniforms: args.set_uniforms,
        })?,
        Command::RenderVideo(args) => ops::render_video_project(&RenderVideoOptions {
            project: args.project,
            output: args.output,
            pass: args.pass,
            width: args.width,
            height: args.height,
            fps: args.fps,
            start_frame: args.start_frame,
            frames: args.frames,
            duration: args.duration,
            codec: args.codec,
            set_uniforms: args.set_uniforms,
        })?,
        Command::Profile(args) => ops::profile_project(&ProfileOptions {
            project: args.project,
            width: args.width,
            height: args.height,
            fps: args.fps,
            frame: args.frame,
            time: args.time,
            warmup: args.warmup,
            samples: args.samples,
            set_uniforms: args.set_uniforms,
        })?,
        Command::Sweep(args) => ops::sweep_project(&SweepOptions {
            project: args.project,
            output_dir: args.output_dir,
            contact_sheet: args.contact_sheet,
            no_contact_sheet: args.no_contact_sheet,
            blind: args.blind,
            columns: args.columns,
            pass: args.pass,
            width: args.width,
            height: args.height,
            fps: args.fps,
            frame: args.frame,
            time: args.time,
            sweep_uniforms: args.sweep_uniforms,
        })?,
        Command::Blind(args) => match args.command {
            BlindCommand::Create(args) => ops::create_blind_comparison(&BlindCreateOptions {
                sources: args.sources,
                output_dir: args.output_dir,
                frames: args.frames,
                width: args.width,
                height: args.height,
                fps: args.fps,
                git_root: args.git_root,
            })?,
            BlindCommand::Judge(args) => ops::judge_blind(&BlindJudgeOptions {
                session: args.session,
                pick: args.pick,
                reason: args.reason,
                reason_file: args.reason_file,
            })?,
            BlindCommand::Reveal(args) => ops::reveal_blind(&BlindRevealOptions {
                session: args.session,
            })?,
        },
        Command::Test(args) => ops::test_project(&TestOptions {
            project: args.project,
            update: args.update,
            filter: args.filter,
        })?,
        Command::Replay(args) => ops::replay_project(&ReplayOptions {
            project: args.project,
            recording: args.recording,
            output: args.output,
            pass: args.pass,
            frame: args.frame,
            allow_project_changes: args.allow_project_changes,
        })?,
        Command::Preview(args) => {
            preview::run(
                PreviewConfig {
                    project: args.project,
                    host: args.host,
                    port: args.port,
                    open: args.open,
                    no_open: args.no_open,
                    token: args.token,
                    preserve_reload_state: !args.reset_on_reload,
                    record: args.record,
                },
                json_mode,
            )?;
            return Ok(None);
        }
        Command::Inspect(args) => match args.command {
            None => ops::inspect_project(&args.project, InspectMode::Summary)?,
            Some(InspectCommand::Graph) => ops::inspect_project(&args.project, InspectMode::Graph)?,
            Some(InspectCommand::Pass { name }) => {
                ops::inspect_project(&args.project, InspectMode::Pass(name))?
            }
            Some(InspectCommand::Channels { name }) => {
                ops::inspect_project(&args.project, InspectMode::Channels(name))?
            }
            Some(InspectCommand::Buffer(buffer)) => ops::inspect_buffer(&InspectBufferOptions {
                project: args.project,
                pass: buffer.name,
                output_index: buffer.output_index,
                width: buffer.width,
                height: buffer.height,
                fps: buffer.fps,
                frame: buffer.frame,
                time: buffer.time,
                pixel: buffer.pixel,
                output: buffer.output,
                raw: buffer.raw,
                visualization: buffer.visualization.into(),
                set_uniforms: buffer.set_uniforms,
            })?,
            Some(InspectCommand::Storage(storage)) => {
                ops::inspect_storage(&InspectStorageOptions {
                    project: args.project,
                    name: storage.name,
                    width: storage.width,
                    height: storage.height,
                    fps: storage.fps,
                    frame: storage.frame,
                    time: storage.time,
                    offset: storage.offset,
                    count: storage.count,
                    value_type: storage.value_type.into(),
                    output: storage.output,
                    set_uniforms: storage.set_uniforms,
                })?
            }
            Some(InspectCommand::State { path }) => ops::inspect_state(&path)?,
        },
        Command::State(args) => match args.command {
            StateCommand::Capture(args) => ops::capture_state(
                &args.project,
                &args.output,
                args.width,
                args.height,
                args.fps,
                args.frame,
                args.time,
                args.include_storage,
                &args.set_uniforms,
            )?,
            StateCommand::Inspect { path } => ops::inspect_state(&path)?,
            StateCommand::Set(args) => {
                ops::set_state_buffers(&args.input, &args.output, &args.assignments)?
            }
            StateCommand::SetStorage(args) => {
                ops::set_state_storage(&args.input, &args.output, &args.assignments)?
            }
        },
        Command::Pass(args) => match args.command {
            PassCommand::Add { name, kind, source } => {
                ops::add_pass(&args.project, &name, kind.into(), source.as_deref())?
            }
            PassCommand::Remove { name, force } => ops::remove_pass(&args.project, &name, force)?,
        },
        Command::Channel(args) => match args.command {
            ChannelCommand::Set {
                pass,
                channel,
                source,
                kind,
                output,
                previous,
                filter,
                wrap,
            } => ops::set_channel(
                &args.project,
                &ChannelSetOptions {
                    pass,
                    channel,
                    source,
                    kind: kind.map(Into::into),
                    output,
                    previous,
                    filter: filter.into(),
                    wrap: wrap.into(),
                },
            )?,
            ChannelCommand::Remove { pass, channel } => {
                ops::remove_channel(&args.project, &pass, channel)?
            }
        },
        Command::Docs(args) => {
            let text = docs::topic(&args.topic, args.schema)?;
            Output {
                human: text.clone(),
                json: json!({
                    "ok": true,
                    "topic": args.topic,
                    "schema": args.schema,
                    "text": text,
                }),
            }
        }
    };
    Ok(Some(output))
}

fn emit(output: Output, json_mode: bool) {
    if json_mode {
        println!(
            "{}",
            serde_json::to_string(&output.json)
                .expect("command output JSON serialization cannot fail")
        );
    } else {
        println!("{}", output.human);
    }
}