sprite-slicer 0.1.0

Sprite-sheet slicing, transparent sprite detection, action grouping, background removal, frame normalization, and GIF preview export.
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
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
//! `sprite-slicer` provides file-oriented helpers for common 2D sprite-sheet
//! workflows.
//!
//! It supports:
//!
//! - slicing a fixed sprite grid into frames
//! - detecting sprites from a transparent sheet
//! - grouping frames into actions
//! - exporting GIF previews
//! - removing a connected background color
//! - normalizing frames onto a shared canvas

use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use anyhow::{Context, Result, bail};
use gif::{Encoder, Frame, Repeat};
use image::RgbaImage;
use serde::{Deserialize, Serialize};

/// Options for slicing a regular sprite sheet into fixed-size frames.
#[derive(Debug, Clone)]
pub struct SliceOptions {
    /// Input sprite sheet path.
    pub input: PathBuf,
    /// Output directory where frames and manifests will be written.
    pub output: PathBuf,
    /// Width of a single frame.
    pub frame_width: u32,
    /// Height of a single frame.
    pub frame_height: u32,
    /// Number of columns in the sheet. When `None`, the value is derived.
    pub columns: Option<u32>,
    /// Number of rows in the sheet. When `None`, the value is derived.
    pub rows: Option<u32>,
    /// Horizontal offset from the left edge of the sheet.
    pub offset_x: u32,
    /// Vertical offset from the top edge of the sheet.
    pub offset_y: u32,
    /// Horizontal gap between frames.
    pub gap_x: u32,
    /// Vertical gap between frames.
    pub gap_y: u32,
    /// When `true`, frames below `min_opaque_pixels` are not exported.
    pub skip_empty: bool,
    /// Pixels with alpha less than or equal to this value count as transparent.
    pub alpha_threshold: u8,
    /// Minimum number of foreground pixels required to keep a frame.
    pub min_opaque_pixels: u32,
    /// Optional background color used to ignore solid-color backdrops.
    pub bg_hex: Option<String>,
    /// Allowed per-channel distance when comparing to `bg_hex`.
    pub bg_threshold: u8,
    /// Output file name for the manifest, usually `frames.toml`.
    pub manifest_name: String,
}

/// Options for detecting disconnected sprites from a transparent or filtered sheet.
#[derive(Debug, Clone)]
pub struct DetectOptions {
    /// Input image path.
    pub input: PathBuf,
    /// Output directory where frames and manifests will be written.
    pub output: PathBuf,
    /// Pixels with alpha less than or equal to this value count as transparent.
    pub alpha_threshold: u8,
    /// Minimum foreground pixel count required for a connected component to be kept.
    pub min_opaque_pixels: u32,
    /// Extra padding added around each detected component.
    pub padding: u32,
    /// Vertical tolerance used when clustering detected components into rows.
    pub row_tolerance: u32,
    /// Optional background color used to ignore solid-color backdrops.
    pub bg_hex: Option<String>,
    /// Allowed per-channel distance when comparing to `bg_hex`.
    pub bg_threshold: u8,
    /// Output file name for the manifest, usually `frames.toml`.
    pub manifest_name: String,
}

/// Options for regrouping sliced frames into named animation folders.
#[derive(Debug, Clone)]
pub struct GroupOptions {
    /// Path to the `frames.toml` manifest generated by `slice_sheet` or `detect_frames`.
    pub manifest: PathBuf,
    /// Path to an action config TOML file.
    pub config: PathBuf,
    /// Output directory where grouped actions will be written.
    pub output: PathBuf,
}

/// Options for exporting PNG frames as a GIF preview.
#[derive(Debug, Clone)]
pub struct GifOptions {
    /// Input PNG file or directory containing PNG frames.
    pub input: PathBuf,
    /// Output GIF file path.
    pub output: PathBuf,
    /// Frames per second for the exported GIF.
    pub fps: u16,
    /// Number of repeats. `0` means infinite looping.
    pub repeat: u16,
    /// Extra padding added around the largest frame.
    pub pad: u32,
}

/// Options for removing a connected background color and producing a transparent PNG.
#[derive(Debug, Clone)]
pub struct RemoveBgOptions {
    /// Input image path.
    pub input: PathBuf,
    /// Output PNG path.
    pub output: PathBuf,
    /// Background color in `#RRGGBB` form.
    pub bg_hex: String,
    /// Allowed per-channel distance when comparing to `bg_hex`.
    pub threshold: u8,
    /// Pixels with alpha less than or equal to this value are treated as already transparent.
    pub alpha_threshold: u8,
}

/// Options for normalizing multiple frames onto a shared canvas and anchor.
#[derive(Debug, Clone)]
pub struct NormalizeOptions {
    /// Input PNG file or directory containing PNG frames.
    pub input: PathBuf,
    /// Output directory for normalized PNG frames.
    pub output: PathBuf,
    /// Target canvas width. When `None`, the maximum input width is used.
    pub width: Option<u32>,
    /// Target canvas height. When `None`, the maximum input height is used.
    pub height: Option<u32>,
    /// Horizontal anchor used to place each frame on the canvas.
    pub anchor_x: AnchorX,
    /// Vertical anchor used to place each frame on the canvas.
    pub anchor_y: AnchorY,
    /// Extra padding added around the final canvas.
    pub pad: u32,
}

/// Result returned by `slice_sheet`.
#[derive(Debug, Clone)]
pub struct SliceOutput {
    /// Path to the generated manifest file.
    pub manifest_path: PathBuf,
    /// Path to the generated index map text file.
    pub index_map_path: PathBuf,
    /// Total number of grid cells examined.
    pub frame_count: usize,
    /// Number of frames actually exported.
    pub kept_frames: usize,
}

/// Result returned by `detect_frames`.
#[derive(Debug, Clone)]
pub struct DetectOutput {
    /// Path to the generated manifest file.
    pub manifest_path: PathBuf,
    /// Path to the generated index map text file.
    pub index_map_path: PathBuf,
    /// Number of detected frames exported.
    pub detected_frames: usize,
    /// Number of row groups inferred from detected components.
    pub rows: usize,
}

/// Summary for one grouped animation action.
#[derive(Debug, Clone)]
pub struct GroupedActionSummary {
    /// Action name, such as `idle` or `walk`.
    pub name: String,
    /// Number of frames exported into that action folder.
    pub frame_count: usize,
}

/// Result returned by `group_actions`.
#[derive(Debug, Clone)]
pub struct GroupOutputSummary {
    /// Path to the generated `actions.toml` summary file.
    pub manifest_path: PathBuf,
    /// Per-action export summaries.
    pub actions: Vec<GroupedActionSummary>,
}

/// Result returned by `export_gif`.
#[derive(Debug, Clone)]
pub struct GifOutput {
    /// Output GIF file path.
    pub output_path: PathBuf,
    /// Number of input frames used.
    pub frame_count: usize,
    /// Final GIF canvas width.
    pub canvas_width: u32,
    /// Final GIF canvas height.
    pub canvas_height: u32,
    /// Effective frames per second.
    pub fps: u16,
}

/// Result returned by `remove_background`.
#[derive(Debug, Clone)]
pub struct RemoveBgOutput {
    /// Output PNG file path.
    pub output_path: PathBuf,
    /// Number of pixels made transparent.
    pub removed_pixels: u32,
}

/// Result returned by `normalize_frames`.
#[derive(Debug, Clone)]
pub struct NormalizeOutput {
    /// Output directory containing normalized PNG frames.
    pub output_dir: PathBuf,
    /// Number of frames written.
    pub frame_count: usize,
    /// Final canvas width.
    pub canvas_width: u32,
    /// Final canvas height.
    pub canvas_height: u32,
    /// Horizontal anchor used during export.
    pub anchor_x: AnchorX,
    /// Vertical anchor used during export.
    pub anchor_y: AnchorY,
}

/// Manifest written by `slice_sheet` and `detect_frames`.
#[derive(Debug, Serialize, Deserialize)]
pub struct SliceManifest {
    /// Absolute or original source image path.
    pub source: PathBuf,
    /// Frame width used for grid slicing. `0` for connected-component detection.
    pub frame_width: u32,
    /// Frame height used for grid slicing. `0` for connected-component detection.
    pub frame_height: u32,
    /// Number of columns in the exported layout.
    pub columns: u32,
    /// Number of rows in the exported layout.
    pub rows: u32,
    /// Horizontal source offset used for grid slicing.
    pub offset_x: u32,
    /// Vertical source offset used for grid slicing.
    pub offset_y: u32,
    /// Horizontal frame gap used for grid slicing.
    pub gap_x: u32,
    /// Vertical frame gap used for grid slicing.
    pub gap_y: u32,
    /// Transparency threshold used during detection.
    pub alpha_threshold: u8,
    /// Minimum opaque pixel threshold used during detection.
    pub min_opaque_pixels: u32,
    /// Optional filtered background color.
    pub bg_hex: Option<String>,
    /// Per-channel background comparison threshold.
    pub bg_threshold: u8,
    /// Detection strategy that produced this manifest.
    pub detection: DetectionMode,
    /// Ordered list of exported or scanned frames.
    pub frames: Vec<FrameRecord>,
}

/// One frame entry in a `SliceManifest`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameRecord {
    /// Stable frame index used by `group_actions`.
    pub index: usize,
    /// Row position in the logical layout.
    pub row: u32,
    /// Column position in the logical layout.
    pub column: u32,
    /// Left edge of the crop rectangle in the source image.
    pub x: u32,
    /// Top edge of the crop rectangle in the source image.
    pub y: u32,
    /// Width of the crop rectangle.
    pub width: u32,
    /// Height of the crop rectangle.
    pub height: u32,
    /// Count of foreground pixels used to evaluate the frame.
    pub opaque_pixels: u32,
    /// Whether the frame was kept and exported.
    pub kept: bool,
    /// Relative output file path if the frame was exported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
}

/// Detection mode recorded in `SliceManifest`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DetectionMode {
    /// Frames were extracted from a fixed row/column grid.
    Grid,
    /// Frames were extracted by connected-component detection.
    ConnectedComponents,
}

/// One action entry in a grouping config file.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ActionSpec {
    /// Action name, such as `idle`, `walk`, or `attack`.
    pub name: String,
    /// Ordered source frame indices included in this action.
    pub frames: Vec<usize>,
}

/// Horizontal anchor used by `normalize_frames`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnchorX {
    /// Align frames to the left side of the target canvas.
    Left,
    /// Center frames horizontally on the target canvas.
    Center,
    /// Align frames to the right side of the target canvas.
    Right,
}

impl fmt::Display for AnchorX {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self {
            Self::Left => "left",
            Self::Center => "center",
            Self::Right => "right",
        };
        f.write_str(value)
    }
}

impl FromStr for AnchorX {
    type Err = String;

    fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
        match input {
            "left" => Ok(Self::Left),
            "center" => Ok(Self::Center),
            "right" => Ok(Self::Right),
            _ => Err(format!("invalid anchor-x: {input}; use left|center|right")),
        }
    }
}

/// Vertical anchor used by `normalize_frames`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnchorY {
    /// Align frames to the top of the target canvas.
    Top,
    /// Center frames vertically on the target canvas.
    Center,
    /// Align frames to the bottom of the target canvas.
    Bottom,
}

impl fmt::Display for AnchorY {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self {
            Self::Top => "top",
            Self::Center => "center",
            Self::Bottom => "bottom",
        };
        f.write_str(value)
    }
}

impl FromStr for AnchorY {
    type Err = String;

    fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
        match input {
            "top" => Ok(Self::Top),
            "center" => Ok(Self::Center),
            "bottom" => Ok(Self::Bottom),
            _ => Err(format!("invalid anchor-y: {input}; use top|center|bottom")),
        }
    }
}

#[derive(Debug, Deserialize)]
struct ActionConfig {
    actions: Vec<ActionSpec>,
}

#[derive(Debug, Serialize)]
struct GroupManifest {
    source_manifest: PathBuf,
    actions: Vec<GroupManifestAction>,
}

#[derive(Debug, Serialize)]
struct GroupManifestAction {
    name: String,
    source_frames: Vec<usize>,
    files: Vec<String>,
}

#[derive(Debug, Clone)]
struct ComponentBounds {
    x: u32,
    y: u32,
    width: u32,
    height: u32,
    opaque_pixels: u32,
    center_y: f32,
}

/// Slice a regular sprite sheet into fixed-size PNG frames.
///
/// This function is intended for sheets with a stable grid layout. It writes
/// `frames/`, a manifest TOML file, and `index-map.txt` into `options.output`.
pub fn slice_sheet(options: SliceOptions) -> Result<SliceOutput> {
    let image = image::open(&options.input)
        .with_context(|| format!("failed to open image {}", options.input.display()))?
        .to_rgba8();

    let columns = options.columns.unwrap_or_else(|| {
        derive_grid_count(image.width(), options.offset_x, options.frame_width, options.gap_x)
    });
    let rows = options.rows.unwrap_or_else(|| {
        derive_grid_count(image.height(), options.offset_y, options.frame_height, options.gap_y)
    });

    validate_grid(
        image.width(),
        image.height(),
        columns,
        rows,
        options.offset_x,
        options.offset_y,
        options.frame_width,
        options.frame_height,
        options.gap_x,
        options.gap_y,
    )?;

    let bg_color = match options.bg_hex.as_deref() {
        Some(value) => Some(parse_hex_color(value)?),
        None => None,
    };

    fs::create_dir_all(&options.output)
        .with_context(|| format!("failed to create {}", options.output.display()))?;
    let frames_dir = options.output.join("frames");
    fs::create_dir_all(&frames_dir)
        .with_context(|| format!("failed to create {}", frames_dir.display()))?;

    let mut frames = Vec::with_capacity((columns * rows) as usize);
    for row in 0..rows {
        for column in 0..columns {
            let x = options.offset_x + column * (options.frame_width + options.gap_x);
            let y = options.offset_y + row * (options.frame_height + options.gap_y);
            let tile = image::imageops::crop_imm(
                &image,
                x,
                y,
                options.frame_width,
                options.frame_height,
            )
            .to_image();
            let opaque_pixels = count_foreground_pixels(
                &tile,
                bg_color,
                options.bg_threshold,
                options.alpha_threshold,
            );
            let kept = !options.skip_empty || opaque_pixels >= options.min_opaque_pixels;
            let index = (row * columns + column) as usize;
            let file = if kept {
                let file_name = format!("frame_{index:04}_r{row:02}_c{column:02}.png");
                let relative = PathBuf::from("frames").join(file_name);
                let full_path = options.output.join(&relative);
                tile.save(&full_path).with_context(|| {
                    format!("failed to save sliced frame {}", full_path.display())
                })?;
                Some(relative.to_string_lossy().to_string())
            } else {
                None
            };

            frames.push(FrameRecord {
                index,
                row,
                column,
                x,
                y,
                width: options.frame_width,
                height: options.frame_height,
                opaque_pixels,
                kept,
                file,
            });
        }
    }

    let manifest = SliceManifest {
        source: canonicalize_if_possible(&options.input),
        frame_width: options.frame_width,
        frame_height: options.frame_height,
        columns,
        rows,
        offset_x: options.offset_x,
        offset_y: options.offset_y,
        gap_x: options.gap_x,
        gap_y: options.gap_y,
        alpha_threshold: options.alpha_threshold,
        min_opaque_pixels: options.min_opaque_pixels,
        bg_hex: options.bg_hex,
        bg_threshold: options.bg_threshold,
        detection: DetectionMode::Grid,
        frames,
    };

    let manifest_path = options.output.join(&options.manifest_name);
    fs::write(&manifest_path, toml::to_string_pretty(&manifest)?)
        .with_context(|| format!("failed to write {}", manifest_path.display()))?;

    let index_map_path = options.output.join("index-map.txt");
    fs::write(&index_map_path, build_index_map(&manifest))
        .with_context(|| format!("failed to write {}", index_map_path.display()))?;

    Ok(SliceOutput {
        manifest_path,
        index_map_path,
        frame_count: manifest.frames.len(),
        kept_frames: manifest.frames.iter().filter(|frame| frame.kept).count(),
    })
}

/// Detect disconnected sprites from a transparent or filtered sprite sheet.
///
/// This function groups connected foreground components, clusters them into
/// rows, and writes PNG frames plus a manifest into `options.output`.
pub fn detect_frames(options: DetectOptions) -> Result<DetectOutput> {
    let image = image::open(&options.input)
        .with_context(|| format!("failed to open image {}", options.input.display()))?
        .to_rgba8();
    let bg_color = match options.bg_hex.as_deref() {
        Some(value) => Some(parse_hex_color(value)?),
        None => None,
    };

    let components = detect_components(
        &image,
        bg_color,
        options.bg_threshold,
        options.alpha_threshold,
        options.min_opaque_pixels,
        options.padding,
    );
    if components.is_empty() {
        bail!("no components matched; lower --min-opaque-pixels or adjust thresholds");
    }

    let rows = assign_rows(&components, options.row_tolerance);
    let max_columns = rows.iter().map(|row| row.len()).max().unwrap_or(0) as u32;

    fs::create_dir_all(&options.output)
        .with_context(|| format!("failed to create {}", options.output.display()))?;
    let frames_dir = options.output.join("frames");
    fs::create_dir_all(&frames_dir)
        .with_context(|| format!("failed to create {}", frames_dir.display()))?;

    let mut frames = Vec::new();
    for (row_index, row) in rows.iter().enumerate() {
        for (column_index, component_index) in row.iter().enumerate() {
            let component = &components[*component_index];
            let tile = image::imageops::crop_imm(
                &image,
                component.x,
                component.y,
                component.width,
                component.height,
            )
            .to_image();
            let index = frames.len();
            let file_name = format!("frame_{index:04}_r{row_index:02}_c{column_index:02}.png");
            let relative = PathBuf::from("frames").join(file_name);
            let full_path = options.output.join(&relative);
            tile.save(&full_path).with_context(|| {
                format!("failed to save detected frame {}", full_path.display())
            })?;

            frames.push(FrameRecord {
                index,
                row: row_index as u32,
                column: column_index as u32,
                x: component.x,
                y: component.y,
                width: component.width,
                height: component.height,
                opaque_pixels: component.opaque_pixels,
                kept: true,
                file: Some(relative.to_string_lossy().to_string()),
            });
        }
    }

    let manifest = SliceManifest {
        source: canonicalize_if_possible(&options.input),
        frame_width: 0,
        frame_height: 0,
        columns: max_columns,
        rows: rows.len() as u32,
        offset_x: 0,
        offset_y: 0,
        gap_x: 0,
        gap_y: 0,
        alpha_threshold: options.alpha_threshold,
        min_opaque_pixels: options.min_opaque_pixels,
        bg_hex: options.bg_hex,
        bg_threshold: options.bg_threshold,
        detection: DetectionMode::ConnectedComponents,
        frames,
    };

    let manifest_path = options.output.join(&options.manifest_name);
    fs::write(&manifest_path, toml::to_string_pretty(&manifest)?)
        .with_context(|| format!("failed to write {}", manifest_path.display()))?;

    let index_map_path = options.output.join("index-map.txt");
    fs::write(&index_map_path, build_sparse_index_map(&rows, &manifest.frames))
        .with_context(|| format!("failed to write {}", index_map_path.display()))?;

    Ok(DetectOutput {
        manifest_path,
        index_map_path,
        detected_frames: manifest.frames.len(),
        rows: rows.len(),
    })
}

/// Regroup frames from a manifest into named animation folders.
///
/// The config file is a TOML document with repeated `[[actions]]` tables
/// containing `name` and `frames`.
pub fn group_actions(options: GroupOptions) -> Result<GroupOutputSummary> {
    let manifest_text = fs::read_to_string(&options.manifest)
        .with_context(|| format!("failed to read {}", options.manifest.display()))?;
    let manifest: SliceManifest = toml::from_str(&manifest_text)
        .with_context(|| format!("failed to parse {}", options.manifest.display()))?;
    let config_text = fs::read_to_string(&options.config)
        .with_context(|| format!("failed to read {}", options.config.display()))?;
    let config: ActionConfig = toml::from_str(&config_text)
        .with_context(|| format!("failed to parse {}", options.config.display()))?;

    fs::create_dir_all(&options.output)
        .with_context(|| format!("failed to create {}", options.output.display()))?;

    let frame_lookup: HashMap<usize, &FrameRecord> =
        manifest.frames.iter().map(|frame| (frame.index, frame)).collect();
    let manifest_root = options
        .manifest
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));

    let mut manifest_actions = Vec::with_capacity(config.actions.len());
    let mut summary = Vec::with_capacity(config.actions.len());

    for action in config.actions {
        let action_dir = options.output.join(&action.name);
        fs::create_dir_all(&action_dir)
            .with_context(|| format!("failed to create {}", action_dir.display()))?;

        let mut exported_files = Vec::with_capacity(action.frames.len());
        for (sequence, frame_index) in action.frames.iter().enumerate() {
            let frame = frame_lookup
                .get(frame_index)
                .copied()
                .with_context(|| format!("frame index {frame_index} is not present in manifest"))?;
            let relative_file = frame.file.as_deref().with_context(|| {
                format!("frame index {frame_index} was not exported; try disabling --skip-empty")
            })?;
            let source_path = manifest_root.join(relative_file);
            let destination_name = format!("{sequence:04}.png");
            let destination_path = action_dir.join(&destination_name);
            fs::copy(&source_path, &destination_path).with_context(|| {
                format!(
                    "failed to copy {} to {}",
                    source_path.display(),
                    destination_path.display()
                )
            })?;
            exported_files.push(
                PathBuf::from(&action.name)
                    .join(destination_name)
                    .to_string_lossy()
                    .to_string(),
            );
        }

        summary.push(GroupedActionSummary {
            name: action.name.clone(),
            frame_count: action.frames.len(),
        });
        manifest_actions.push(GroupManifestAction {
            name: action.name,
            source_frames: action.frames,
            files: exported_files,
        });
    }

    let grouped_manifest = GroupManifest {
        source_manifest: canonicalize_if_possible(&options.manifest),
        actions: manifest_actions,
    };
    let manifest_path = options.output.join("actions.toml");
    fs::write(&manifest_path, toml::to_string_pretty(&grouped_manifest)?)
        .with_context(|| format!("failed to write {}", manifest_path.display()))?;

    Ok(GroupOutputSummary {
        manifest_path,
        actions: summary,
    })
}

/// Export one PNG or a directory of PNG frames into a preview GIF.
///
/// When the input is a directory, only the top-level PNG files are read and
/// then sorted by file name before export.
pub fn export_gif(options: GifOptions) -> Result<GifOutput> {
    let mut frame_paths = collect_png_files(&options.input)?;
    if frame_paths.is_empty() {
        bail!("no png frames found under {}", options.input.display());
    }
    frame_paths.sort();

    let mut decoded_frames = Vec::with_capacity(frame_paths.len());
    let mut canvas_width = 0_u32;
    let mut canvas_height = 0_u32;

    for path in &frame_paths {
        let image = image::open(path)
            .with_context(|| format!("failed to open frame {}", path.display()))?
            .to_rgba8();
        canvas_width = canvas_width.max(image.width());
        canvas_height = canvas_height.max(image.height());
        decoded_frames.push(image);
    }

    canvas_width += options.pad * 2;
    canvas_height += options.pad * 2;

    if canvas_width > u16::MAX as u32 || canvas_height > u16::MAX as u32 {
        bail!("gif canvas too large: {}x{}", canvas_width, canvas_height);
    }

    if let Some(parent) = options.output.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    let file = fs::File::create(&options.output)
        .with_context(|| format!("failed to create {}", options.output.display()))?;
    let mut encoder = Encoder::new(file, canvas_width as u16, canvas_height as u16, &[])
        .with_context(|| format!("failed to initialize gif {}", options.output.display()))?;

    if options.repeat == 0 {
        encoder.set_repeat(Repeat::Infinite)?;
    } else {
        encoder.set_repeat(Repeat::Finite(options.repeat))?;
    }

    let delay = fps_to_gif_delay(options.fps);

    for image in decoded_frames {
        let mut canvas = RgbaImage::new(canvas_width, canvas_height);
        let offset_x = ((canvas_width - image.width()) / 2) as i64;
        let offset_y = ((canvas_height - image.height()) / 2) as i64;
        image::imageops::overlay(&mut canvas, &image, offset_x, offset_y);

        let mut rgba = canvas.into_raw();
        let mut frame =
            Frame::from_rgba_speed(canvas_width as u16, canvas_height as u16, &mut rgba, 10);
        frame.delay = delay;
        encoder
            .write_frame(&frame)
            .with_context(|| format!("failed writing gif frame to {}", options.output.display()))?;
    }

    Ok(GifOutput {
        output_path: options.output,
        frame_count: frame_paths.len(),
        canvas_width,
        canvas_height,
        fps: options.fps,
    })
}

/// Remove a connected background color and save the result as a transparent PNG.
///
/// Only regions connected to the image boundary are removed, which helps keep
/// internal dark outlines or details intact.
pub fn remove_background(options: RemoveBgOptions) -> Result<RemoveBgOutput> {
    let mut image = image::open(&options.input)
        .with_context(|| format!("failed to open image {}", options.input.display()))?
        .to_rgba8();
    let bg_color = parse_hex_color(&options.bg_hex)?;
    let removed_pixels = remove_connected_background(
        &mut image,
        bg_color,
        options.threshold,
        options.alpha_threshold,
    );

    if let Some(parent) = options.output.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    image
        .save(&options.output)
        .with_context(|| format!("failed to save {}", options.output.display()))?;

    Ok(RemoveBgOutput {
        output_path: options.output,
        removed_pixels,
    })
}

/// Normalize one PNG or a directory of PNG frames onto a shared canvas.
///
/// This is typically used before importing animation frames into a game engine
/// so that position changes between actions stay visually stable.
pub fn normalize_frames(options: NormalizeOptions) -> Result<NormalizeOutput> {
    let mut frame_paths = collect_png_files(&options.input)?;
    if frame_paths.is_empty() {
        bail!("no png frames found under {}", options.input.display());
    }
    frame_paths.sort();

    let mut images = Vec::with_capacity(frame_paths.len());
    let mut target_width = options.width.unwrap_or(0);
    let mut target_height = options.height.unwrap_or(0);

    for path in &frame_paths {
        let image = image::open(path)
            .with_context(|| format!("failed to open frame {}", path.display()))?
            .to_rgba8();
        target_width = target_width.max(image.width());
        target_height = target_height.max(image.height());
        images.push(image);
    }

    target_width += options.pad * 2;
    target_height += options.pad * 2;

    fs::create_dir_all(&options.output)
        .with_context(|| format!("failed to create {}", options.output.display()))?;

    for (index, image) in images.into_iter().enumerate() {
        let mut canvas = RgbaImage::new(target_width, target_height);
        let offset_x = horizontal_offset(target_width, image.width(), options.pad, options.anchor_x);
        let offset_y =
            vertical_offset(target_height, image.height(), options.pad, options.anchor_y);
        image::imageops::overlay(&mut canvas, &image, offset_x as i64, offset_y as i64);

        let output_name = format!("{index:04}.png");
        let output_path = options.output.join(output_name);
        canvas
            .save(&output_path)
            .with_context(|| format!("failed to save {}", output_path.display()))?;
    }

    Ok(NormalizeOutput {
        output_dir: options.output,
        frame_count: frame_paths.len(),
        canvas_width: target_width,
        canvas_height: target_height,
        anchor_x: options.anchor_x,
        anchor_y: options.anchor_y,
    })
}

fn derive_grid_count(total: u32, offset: u32, frame: u32, gap: u32) -> u32 {
    if total <= offset || total < offset + frame {
        return 0;
    }
    let step = frame + gap;
    1 + (total - offset - frame) / step
}

fn validate_grid(
    image_width: u32,
    image_height: u32,
    columns: u32,
    rows: u32,
    offset_x: u32,
    offset_y: u32,
    frame_width: u32,
    frame_height: u32,
    gap_x: u32,
    gap_y: u32,
) -> Result<()> {
    if columns == 0 || rows == 0 {
        bail!("grid resolved to zero columns or rows");
    }

    let last_right = offset_x + columns * frame_width + columns.saturating_sub(1) * gap_x;
    let last_bottom = offset_y + rows * frame_height + rows.saturating_sub(1) * gap_y;
    if last_right > image_width || last_bottom > image_height {
        bail!(
            "grid exceeds image bounds: need {}x{}, image is {}x{}",
            last_right,
            last_bottom,
            image_width,
            image_height
        );
    }

    Ok(())
}

fn parse_hex_color(input: &str) -> Result<[u8; 3]> {
    let trimmed = input.trim().trim_start_matches('#');
    if trimmed.len() != 6 {
        bail!("background color must be a 6-digit hex value, got {input}");
    }

    let red = u8::from_str_radix(&trimmed[0..2], 16)
        .with_context(|| format!("invalid red channel in {input}"))?;
    let green = u8::from_str_radix(&trimmed[2..4], 16)
        .with_context(|| format!("invalid green channel in {input}"))?;
    let blue = u8::from_str_radix(&trimmed[4..6], 16)
        .with_context(|| format!("invalid blue channel in {input}"))?;

    Ok([red, green, blue])
}

fn count_foreground_pixels(
    image: &RgbaImage,
    bg_color: Option<[u8; 3]>,
    bg_threshold: u8,
    alpha_threshold: u8,
) -> u32 {
    image
        .pixels()
        .filter(|pixel| {
            if pixel[3] <= alpha_threshold {
                return false;
            }

            match bg_color {
                Some(color) => {
                    !channels_close([pixel[0], pixel[1], pixel[2]], color, bg_threshold)
                }
                None => true,
            }
        })
        .count() as u32
}

fn detect_components(
    image: &RgbaImage,
    bg_color: Option<[u8; 3]>,
    bg_threshold: u8,
    alpha_threshold: u8,
    min_opaque_pixels: u32,
    padding: u32,
) -> Vec<ComponentBounds> {
    let width = image.width() as usize;
    let height = image.height() as usize;
    let mut foreground = vec![false; width * height];

    for y in 0..height {
        for x in 0..width {
            let pixel = image.get_pixel(x as u32, y as u32);
            let is_foreground = pixel[3] > alpha_threshold
                && match bg_color {
                    Some(color) => {
                        !channels_close([pixel[0], pixel[1], pixel[2]], color, bg_threshold)
                    }
                    None => true,
                };
            foreground[y * width + x] = is_foreground;
        }
    }

    let mut visited = vec![false; width * height];
    let mut components = Vec::new();

    for y in 0..height {
        for x in 0..width {
            let start = y * width + x;
            if !foreground[start] || visited[start] {
                continue;
            }

            let mut queue = VecDeque::from([(x as u32, y as u32)]);
            visited[start] = true;

            let mut min_x = x as u32;
            let mut max_x = x as u32;
            let mut min_y = y as u32;
            let mut max_y = y as u32;
            let mut opaque_pixels = 0_u32;

            while let Some((cx, cy)) = queue.pop_front() {
                opaque_pixels += 1;
                min_x = min_x.min(cx);
                max_x = max_x.max(cx);
                min_y = min_y.min(cy);
                max_y = max_y.max(cy);

                for (nx, ny) in neighbors(cx, cy, image.width(), image.height()) {
                    let idx = ny as usize * width + nx as usize;
                    if foreground[idx] && !visited[idx] {
                        visited[idx] = true;
                        queue.push_back((nx, ny));
                    }
                }
            }

            if opaque_pixels < min_opaque_pixels {
                continue;
            }

            let padded_x = min_x.saturating_sub(padding);
            let padded_y = min_y.saturating_sub(padding);
            let padded_right = (max_x + 1 + padding).min(image.width());
            let padded_bottom = (max_y + 1 + padding).min(image.height());
            let padded_width = padded_right - padded_x;
            let padded_height = padded_bottom - padded_y;

            components.push(ComponentBounds {
                x: padded_x,
                y: padded_y,
                width: padded_width,
                height: padded_height,
                opaque_pixels,
                center_y: (min_y + max_y) as f32 / 2.0,
            });
        }
    }

    components.sort_by(|left, right| {
        left.y
            .cmp(&right.y)
            .then(left.x.cmp(&right.x))
            .then(right.opaque_pixels.cmp(&left.opaque_pixels))
    });
    components
}

fn neighbors(x: u32, y: u32, width: u32, height: u32) -> impl Iterator<Item = (u32, u32)> {
    let mut items = Vec::with_capacity(8);
    for dy in -1_i32..=1 {
        for dx in -1_i32..=1 {
            if dx == 0 && dy == 0 {
                continue;
            }
            let nx = x as i32 + dx;
            let ny = y as i32 + dy;
            if nx >= 0 && ny >= 0 && nx < width as i32 && ny < height as i32 {
                items.push((nx as u32, ny as u32));
            }
        }
    }
    items.into_iter()
}

fn assign_rows(components: &[ComponentBounds], row_tolerance: u32) -> Vec<Vec<usize>> {
    let mut order: Vec<usize> = (0..components.len()).collect();
    order.sort_by(|left, right| {
        components[*left]
            .center_y
            .total_cmp(&components[*right].center_y)
            .then(components[*left].x.cmp(&components[*right].x))
    });

    let mut rows: Vec<Vec<usize>> = Vec::new();
    let mut row_centers: Vec<f32> = Vec::new();

    for component_index in order {
        let center_y = components[component_index].center_y;
        if let Some((row_index, _)) = row_centers
            .iter()
            .enumerate()
            .find(|(_, row_center)| (center_y - **row_center).abs() <= row_tolerance as f32)
        {
            rows[row_index].push(component_index);
            let count = rows[row_index].len() as f32;
            row_centers[row_index] = ((row_centers[row_index] * (count - 1.0)) + center_y) / count;
        } else {
            rows.push(vec![component_index]);
            row_centers.push(center_y);
        }
    }

    for row in &mut rows {
        row.sort_by_key(|component_index| components[*component_index].x);
    }

    rows.sort_by_key(|row| components[row[0]].y);
    rows
}

fn channels_close(lhs: [u8; 3], rhs: [u8; 3], threshold: u8) -> bool {
    lhs.into_iter()
        .zip(rhs)
        .all(|(left, right)| left.abs_diff(right) <= threshold)
}

fn build_index_map(manifest: &SliceManifest) -> String {
    let digits = manifest
        .frames
        .len()
        .saturating_sub(1)
        .to_string()
        .len()
        .max(4);
    let mut output = String::new();

    for row in 0..manifest.rows {
        for column in 0..manifest.columns {
            let index = (row * manifest.columns + column) as usize;
            let frame = &manifest.frames[index];
            if frame.kept {
                output.push_str(&format!("{:0digits$}", frame.index));
            } else {
                output.push_str(&"-".repeat(digits));
            }
            if column + 1 < manifest.columns {
                output.push(' ');
            }
        }
        output.push('\n');
    }

    output
}

fn build_sparse_index_map(rows: &[Vec<usize>], frames: &[FrameRecord]) -> String {
    let digits = frames
        .len()
        .saturating_sub(1)
        .to_string()
        .len()
        .max(4);
    let mut output = String::new();

    for row in rows {
        for (position, frame_index) in row.iter().enumerate() {
            output.push_str(&format!("{:0digits$}", frames[*frame_index].index));
            if position + 1 < row.len() {
                output.push(' ');
            }
        }
        output.push('\n');
    }

    output
}

fn collect_png_files(input: &Path) -> Result<Vec<PathBuf>> {
    if input.is_file() {
        if is_png(input) {
            return Ok(vec![input.to_path_buf()]);
        }
        bail!("input file is not a png: {}", input.display());
    }

    if !input.is_dir() {
        bail!("input path does not exist: {}", input.display());
    }

    let mut files = Vec::new();
    for entry in fs::read_dir(input).with_context(|| format!("failed to read {}", input.display()))?
    {
        let path = entry?.path();
        if path.is_file() && is_png(&path) {
            files.push(path);
        }
    }
    Ok(files)
}

fn is_png(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.eq_ignore_ascii_case("png"))
        .unwrap_or(false)
}

fn fps_to_gif_delay(fps: u16) -> u16 {
    let fps = fps.max(1) as f32;
    ((100.0 / fps).round() as u16).max(1)
}

fn remove_connected_background(
    image: &mut RgbaImage,
    bg_color: [u8; 3],
    threshold: u8,
    alpha_threshold: u8,
) -> u32 {
    let width = image.width() as usize;
    let height = image.height() as usize;
    let mut visited = vec![false; width * height];
    let mut queue = VecDeque::new();

    for x in 0..image.width() {
        queue_if_background(
            image,
            x,
            0,
            bg_color,
            threshold,
            alpha_threshold,
            &mut visited,
            &mut queue,
        );
        if image.height() > 1 {
            queue_if_background(
                image,
                x,
                image.height() - 1,
                bg_color,
                threshold,
                alpha_threshold,
                &mut visited,
                &mut queue,
            );
        }
    }

    for y in 0..image.height() {
        queue_if_background(
            image,
            0,
            y,
            bg_color,
            threshold,
            alpha_threshold,
            &mut visited,
            &mut queue,
        );
        if image.width() > 1 {
            queue_if_background(
                image,
                image.width() - 1,
                y,
                bg_color,
                threshold,
                alpha_threshold,
                &mut visited,
                &mut queue,
            );
        }
    }

    let mut removed = 0_u32;
    while let Some((x, y)) = queue.pop_front() {
        let pixel = image.get_pixel_mut(x, y);
        if pixel[3] != 0 {
            pixel[3] = 0;
            removed += 1;
        }

        for (nx, ny) in neighbors(x, y, image.width(), image.height()) {
            let idx = ny as usize * width + nx as usize;
            if visited[idx] {
                continue;
            }
            let neighbor = image.get_pixel(nx, ny);
            if neighbor[3] <= alpha_threshold {
                visited[idx] = true;
                continue;
            }
            if channels_close([neighbor[0], neighbor[1], neighbor[2]], bg_color, threshold) {
                visited[idx] = true;
                queue.push_back((nx, ny));
            }
        }
    }

    removed
}

fn queue_if_background(
    image: &RgbaImage,
    x: u32,
    y: u32,
    bg_color: [u8; 3],
    threshold: u8,
    alpha_threshold: u8,
    visited: &mut [bool],
    queue: &mut VecDeque<(u32, u32)>,
) {
    let idx = y as usize * image.width() as usize + x as usize;
    if visited[idx] {
        return;
    }
    let pixel = image.get_pixel(x, y);
    if pixel[3] <= alpha_threshold
        || channels_close([pixel[0], pixel[1], pixel[2]], bg_color, threshold)
    {
        visited[idx] = true;
        queue.push_back((x, y));
    }
}

fn horizontal_offset(target_width: u32, frame_width: u32, pad: u32, anchor: AnchorX) -> u32 {
    match anchor {
        AnchorX::Left => pad,
        AnchorX::Center => (target_width.saturating_sub(frame_width)) / 2,
        AnchorX::Right => target_width.saturating_sub(frame_width + pad),
    }
}

fn vertical_offset(target_height: u32, frame_height: u32, pad: u32, anchor: AnchorY) -> u32 {
    match anchor {
        AnchorY::Top => pad,
        AnchorY::Center => (target_height.saturating_sub(frame_height)) / 2,
        AnchorY::Bottom => target_height.saturating_sub(frame_height + pad),
    }
}

fn canonicalize_if_possible(path: &Path) -> PathBuf {
    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

#[cfg(test)]
mod tests {
    use super::{
        AnchorX, AnchorY, ComponentBounds, DetectionMode, FrameRecord, SliceManifest, assign_rows,
        build_index_map, build_sparse_index_map, channels_close, derive_grid_count,
        fps_to_gif_delay, horizontal_offset, parse_hex_color, vertical_offset,
    };
    use std::path::PathBuf;

    #[test]
    fn parses_hex_color() {
        assert_eq!(parse_hex_color("#12abEF").unwrap(), [0x12, 0xab, 0xef]);
        assert!(parse_hex_color("xyz").is_err());
    }

    #[test]
    fn derives_grid_count_from_image_size() {
        assert_eq!(derive_grid_count(256, 0, 64, 0), 4);
        assert_eq!(derive_grid_count(250, 10, 60, 5), 3);
    }

    #[test]
    fn compares_channels_with_threshold() {
        assert!(channels_close([0, 0, 0], [1, 1, 1], 1));
        assert!(!channels_close([0, 0, 0], [2, 2, 2], 1));
    }

    #[test]
    fn builds_index_map_with_empty_cells() {
        let manifest = SliceManifest {
            source: PathBuf::from("sheet.png"),
            frame_width: 64,
            frame_height: 64,
            columns: 2,
            rows: 2,
            offset_x: 0,
            offset_y: 0,
            gap_x: 0,
            gap_y: 0,
            alpha_threshold: 0,
            min_opaque_pixels: 1,
            bg_hex: None,
            bg_threshold: 0,
            detection: DetectionMode::Grid,
            frames: vec![
                FrameRecord {
                    index: 0,
                    row: 0,
                    column: 0,
                    x: 0,
                    y: 0,
                    width: 64,
                    height: 64,
                    opaque_pixels: 10,
                    kept: true,
                    file: Some("frames/frame_0000.png".to_string()),
                },
                FrameRecord {
                    index: 1,
                    row: 0,
                    column: 1,
                    x: 64,
                    y: 0,
                    width: 64,
                    height: 64,
                    opaque_pixels: 0,
                    kept: false,
                    file: None,
                },
                FrameRecord {
                    index: 2,
                    row: 1,
                    column: 0,
                    x: 0,
                    y: 64,
                    width: 64,
                    height: 64,
                    opaque_pixels: 8,
                    kept: true,
                    file: Some("frames/frame_0002.png".to_string()),
                },
                FrameRecord {
                    index: 3,
                    row: 1,
                    column: 1,
                    x: 64,
                    y: 64,
                    width: 64,
                    height: 64,
                    opaque_pixels: 9,
                    kept: true,
                    file: Some("frames/frame_0003.png".to_string()),
                },
            ],
        };

        assert_eq!(build_index_map(&manifest), "0000 ----\n0002 0003\n");
    }

    #[test]
    fn assigns_rows_from_detected_components() {
        let components = vec![
            ComponentBounds {
                x: 10,
                y: 10,
                width: 20,
                height: 20,
                opaque_pixels: 100,
                center_y: 20.0,
            },
            ComponentBounds {
                x: 60,
                y: 12,
                width: 20,
                height: 20,
                opaque_pixels: 100,
                center_y: 22.0,
            },
            ComponentBounds {
                x: 15,
                y: 70,
                width: 20,
                height: 20,
                opaque_pixels: 100,
                center_y: 80.0,
            },
        ];

        let rows = assign_rows(&components, 8);
        assert_eq!(rows, vec![vec![0, 1], vec![2]]);
    }

    #[test]
    fn builds_sparse_index_map_for_detected_layout() {
        let rows = vec![vec![0, 1], vec![2]];
        let frames = vec![
            FrameRecord {
                index: 0,
                row: 0,
                column: 0,
                x: 0,
                y: 0,
                width: 10,
                height: 10,
                opaque_pixels: 10,
                kept: true,
                file: Some("frames/0.png".to_string()),
            },
            FrameRecord {
                index: 1,
                row: 0,
                column: 1,
                x: 10,
                y: 0,
                width: 10,
                height: 10,
                opaque_pixels: 10,
                kept: true,
                file: Some("frames/1.png".to_string()),
            },
            FrameRecord {
                index: 2,
                row: 1,
                column: 0,
                x: 0,
                y: 10,
                width: 10,
                height: 10,
                opaque_pixels: 10,
                kept: true,
                file: Some("frames/2.png".to_string()),
            },
        ];

        assert_eq!(build_sparse_index_map(&rows, &frames), "0000 0001\n0002\n");
    }

    #[test]
    fn converts_fps_to_gif_delay() {
        assert_eq!(fps_to_gif_delay(10), 10);
        assert_eq!(fps_to_gif_delay(8), 13);
        assert_eq!(fps_to_gif_delay(0), 100);
    }

    #[test]
    fn computes_offsets() {
        assert_eq!(horizontal_offset(128, 64, 4, AnchorX::Center), 32);
        assert_eq!(horizontal_offset(128, 64, 4, AnchorX::Right), 60);
        assert_eq!(vertical_offset(128, 64, 4, AnchorY::Bottom), 60);
        assert_eq!(vertical_offset(128, 64, 4, AnchorY::Top), 4);
    }
}