rust_pixel 2.4.0

2d pixel-art game engine & rapid prototype tools support terminal, wgpu and web...
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
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
// RustPixel
// copyright zipxing@hotmail.com 2022~2026

//! # Visual Effects System
//!
//! This module provides a unified system for visual effects, supporting both:
//! - **CPU Effects (BufferEffect)**: Cell-level effects on Buffer
//! - **GPU Effects (GpuTransition)**: Pixel-level shader effects on RenderTextures
//!
//! ## Architecture
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │                     Visual Effects System                            │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │  CPU Effects (BufferEffect trait)                                    │
//! │    - 操作对象: Buffer (字符级别)                                      │
//! │    - 执行位置: CPU                                                    │
//! │    - apply(&self, src: &Buffer, dst: &mut Buffer, params)            │
//! │                                                                      │
//! │  Built-in CPU Effects:                                               │
//! │    - WaveEffect      (水平波浪扭曲)                                   │
//! │    - RippleEffect    (中心涟漪扩散)                                   │
//! │    - SwirlEffect     (漩涡旋转)                                       │
//! │    - NoiseEffect     (随机噪点)                                       │
//! │    - FadeEffect      (透明度渐变)                                     │
//! │    - PixelateEffect  (马赛克像素化)                                   │
//! │    - BlurEffect      (简单模糊)                                       │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │  GPU Effects (GpuTransition enum)                                    │
//! │    - 操作对象: RenderTexture (像素级别)                               │
//! │    - 执行位置: GPU (via GLSL shaders)                                 │
//! │    - 通过 Adapter::blend_rts() 调用                                   │
//! │                                                                      │
//! │  Built-in GPU Transitions (7种):                                     │
//! │    - Squares     (方格渐变)                                           │
//! │    - Heart       (心形展开)                                           │
//! │    - Noise       (噪点过渡)                                           │
//! │    - RotateZoom  (旋转缩放)                                           │
//! │    - Bounce      (弹跳波浪)                                           │
//! │    - Dispersion  (色散分离)                                           │
//! │    - Ripple      (涟漪扩散)                                           │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │  EffectChain: 组合多个CPU特效                                         │
//! │  GpuBlendEffect: GPU混合特效描述                                      │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Usage Example
//! ```ignore
//! use rust_pixel::render::effect::*;
//!
//! // === CPU Effects (Buffer级别) ===
//! let wave = WaveEffect::new(0.03, 15.0);
//! let ripple = RippleEffect::new(0.05, 10.0);
//! let mut chain = EffectChain::new();
//! chain.add(Box::new(wave));
//! chain.add(Box::new(ripple));
//! let params = EffectParams::new(0.5, stage);
//! chain.apply(&src_buffer, &mut dst_buffer, &params);
//!
//! // === GPU Effects (RenderTexture级别) ===
//! let gpu_effect = GpuBlendEffect::ripple(0.5);
//! ctx.adapter.blend_rts(
//!     0, 1, 2,                    // src1, src2, dst RT索引
//!     gpu_effect.effect_type(),   // 特效类型
//!     gpu_effect.progress         // 进度
//! );
//! ```

use crate::render::buffer::Buffer;
use crate::render::cell::cellsym;
use crate::render::style::Color;

// ============================================================================
// GPU Transition Effects (Shader-based, 像素级别)
// ============================================================================

/// GPU过渡特效类型
///
/// 这些特效在GPU上通过GLSL着色器执行,用于两个RenderTexture之间的混合过渡。
/// 对应 `shader_source.rs` 中的 `TRANS_FS` 着色器数组。
///
/// # 工作原理
/// ```text
/// ┌─────────────┐     ┌─────────────┐
/// │   RT1 (源1) │     │   RT2 (源2) │
/// └──────┬──────┘     └──────┬──────┘
///        │                   │
///        └─────────┬─────────┘
//////        ┌─────────────────────┐
///        │   GPU Transition    │  ← progress (0.0~1.0)
///        │   (GLSL Shader)     │
///        └──────────┬──────────┘
//////           ┌─────────────┐
///           │   RT (目标)  │
///           └─────────────┘
/// ```
///
/// # 使用方式
/// ```ignore
/// let transition = GpuTransition::Ripple;
/// ctx.adapter.blend_rts(
///     src_rt1,           // 源RT1索引 (过渡起始画面)
///     src_rt2,           // 源RT2索引 (过渡目标画面)
///     dst_rt,            // 目标RT索引 (混合结果)
///     transition.into(), // 特效类型转为usize
///     progress,          // 进度 0.0(全src1) ~ 1.0(全src2)
/// );
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(usize)]
#[derive(Default)]
pub enum GpuTransition {
    /// 方格渐变过渡 (Squares Grid)
    ///
    /// 画面被分割成动态大小的方格,方格内容逐渐从源图像过渡到目标图像。
    /// 方格大小随进度变化,产生像素化的过渡效果。
    ///
    /// 适合场景:复古风格场景切换、像素艺术游戏
    #[default]
    Squares = 0,

    /// 心形展开过渡 (Heart Shape)
    ///
    /// 从画面中心以心形向外展开,逐渐显示目标图像。
    /// 使用数学公式生成心形轮廓。
    ///
    /// 适合场景:恋爱游戏、节日活动、特殊奖励
    Heart = 1,

    /// 噪点过渡 (Static Noise)
    ///
    /// 通过随机噪点实现电视雪花般的过渡效果。
    /// 在过渡中间阶段显示纯噪点。
    ///
    /// 适合场景:信号干扰、故障艺术、恐怖氛围
    Noise = 2,

    /// 旋转缩放过渡 (Rotate & Zoom)
    ///
    /// 画面同时进行旋转和缩放变换,产生眩晕般的过渡效果。
    /// 前半段旋转放大,后半段旋转缩小恢复。
    ///
    /// 适合场景:时空穿越、回忆闪回、梦境切换
    RotateZoom = 3,

    /// 弹跳波浪过渡 (Bounce Wave)
    ///
    /// 源图像像弹跳的球一样从底部弹起消失,逐渐显示目标图像。
    /// 使用正弦函数实现弹跳曲线。
    ///
    /// 适合场景:轻快的场景切换、游戏关卡过渡
    Bounce = 4,

    /// 色散分离过渡 (Color Dispersion)
    ///
    /// RGB三通道产生不同程度的位移,产生色差/色散效果。
    /// 同时添加波浪扭曲增强视觉冲击。
    ///
    /// 适合场景:冲击波、能量释放、赛博朋克风格
    Dispersion = 5,

    /// 涟漪扩散过渡 (Ripple Wave)
    ///
    /// 从中心向外扩散的同心圆水波纹效果。
    /// 波纹内部显示混合后的画面,外部保持原画面。
    ///
    /// 适合场景:水面效果、能量场、传送门
    Ripple = 6,
}

impl GpuTransition {
    /// 获取所有GPU过渡类型的数组引用
    pub fn all() -> &'static [GpuTransition] {
        &[
            GpuTransition::Squares,
            GpuTransition::Heart,
            GpuTransition::Noise,
            GpuTransition::RotateZoom,
            GpuTransition::Bounce,
            GpuTransition::Dispersion,
            GpuTransition::Ripple,
        ]
    }

    /// 获取特效英文名称
    pub fn name(&self) -> &'static str {
        match self {
            GpuTransition::Squares => "Squares",
            GpuTransition::Heart => "Heart",
            GpuTransition::Noise => "Noise",
            GpuTransition::RotateZoom => "RotateZoom",
            GpuTransition::Bounce => "Bounce",
            GpuTransition::Dispersion => "Dispersion",
            GpuTransition::Ripple => "Ripple",
        }
    }

    /// 获取特效中文名称
    pub fn name_cn(&self) -> &'static str {
        match self {
            GpuTransition::Squares => "方格渐变",
            GpuTransition::Heart => "心形展开",
            GpuTransition::Noise => "噪点过渡",
            GpuTransition::RotateZoom => "旋转缩放",
            GpuTransition::Bounce => "弹跳波浪",
            GpuTransition::Dispersion => "色散分离",
            GpuTransition::Ripple => "涟漪扩散",
        }
    }

    /// 获取特效详细描述
    pub fn description(&self) -> &'static str {
        match self {
            GpuTransition::Squares => "Grid squares transition with dynamic sizing",
            GpuTransition::Heart => "Heart-shaped reveal from center",
            GpuTransition::Noise => "TV static noise transition",
            GpuTransition::RotateZoom => "Rotation with zoom in/out effect",
            GpuTransition::Bounce => "Bouncing wave wipe transition",
            GpuTransition::Dispersion => "RGB chromatic aberration effect",
            GpuTransition::Ripple => "Circular ripple wave from center",
        }
    }

    /// 获取GPU过渡特效总数
    pub const fn count() -> usize {
        7
    }

    /// 从索引创建 (循环取模,确保总是有效)
    pub fn from_index(index: usize) -> Self {
        match index % Self::count() {
            0 => GpuTransition::Squares,
            1 => GpuTransition::Heart,
            2 => GpuTransition::Noise,
            3 => GpuTransition::RotateZoom,
            4 => GpuTransition::Bounce,
            5 => GpuTransition::Dispersion,
            _ => GpuTransition::Ripple,
        }
    }

    /// 获取下一个过渡类型 (循环)
    pub fn next(&self) -> Self {
        Self::from_index(*self as usize + 1)
    }

    /// 获取上一个过渡类型 (循环)
    pub fn prev(&self) -> Self {
        let idx = *self as usize;
        Self::from_index(if idx == 0 { Self::count() - 1 } else { idx - 1 })
    }
}

impl From<GpuTransition> for usize {
    fn from(t: GpuTransition) -> Self {
        t as usize
    }
}

impl From<usize> for GpuTransition {
    fn from(v: usize) -> Self {
        GpuTransition::from_index(v)
    }
}


/// GPU混合特效描述
///
/// 封装了GPU过渡特效的完整参数,便于传递和复用。
/// 提供便捷的工厂方法创建各种过渡效果。
///
/// # Example
/// ```ignore
/// // 方式1: 使用new
/// let effect = GpuBlendEffect::new(GpuTransition::Ripple, 0.5);
///
/// // 方式2: 使用工厂方法
/// let effect = GpuBlendEffect::ripple(0.5);
/// let effect = GpuBlendEffect::dispersion(0.3);
///
/// // 调用blend_rts
/// ctx.adapter.blend_rts(0, 1, 2, effect.effect_type(), effect.progress);
/// ```
#[derive(Clone, Debug)]
pub struct GpuBlendEffect {
    /// 过渡特效类型
    pub transition: GpuTransition,
    /// 过渡进度 (0.0 = 完全显示src1, 1.0 = 完全显示src2)
    pub progress: f32,
}

impl GpuBlendEffect {
    /// 创建新的GPU混合特效
    ///
    /// # Parameters
    /// - `transition`: 过渡类型
    /// - `progress`: 过渡进度 (0.0 ~ 1.0)
    pub fn new(transition: GpuTransition, progress: f32) -> Self {
        Self {
            transition,
            progress: progress.clamp(0.0, 1.0),
        }
    }

    /// 获取特效类型索引 (用于 Adapter::blend_rts)
    #[inline]
    pub fn effect_type(&self) -> usize {
        self.transition as usize
    }

    /// 设置进度值
    pub fn with_progress(mut self, progress: f32) -> Self {
        self.progress = progress.clamp(0.0, 1.0);
        self
    }

    /// 更新进度值 (可变引用版本)
    pub fn set_progress(&mut self, progress: f32) {
        self.progress = progress.clamp(0.0, 1.0);
    }

    // === 工厂方法 (Factory Methods) ===

    /// 创建方格过渡特效
    pub fn squares(progress: f32) -> Self {
        Self::new(GpuTransition::Squares, progress)
    }

    /// 创建心形过渡特效
    pub fn heart(progress: f32) -> Self {
        Self::new(GpuTransition::Heart, progress)
    }

    /// 创建噪点过渡特效
    pub fn noise(progress: f32) -> Self {
        Self::new(GpuTransition::Noise, progress)
    }

    /// 创建旋转缩放过渡特效
    pub fn rotate_zoom(progress: f32) -> Self {
        Self::new(GpuTransition::RotateZoom, progress)
    }

    /// 创建弹跳波浪过渡特效
    pub fn bounce(progress: f32) -> Self {
        Self::new(GpuTransition::Bounce, progress)
    }

    /// 创建色散过渡特效
    pub fn dispersion(progress: f32) -> Self {
        Self::new(GpuTransition::Dispersion, progress)
    }

    /// 创建涟漪过渡特效
    pub fn ripple(progress: f32) -> Self {
        Self::new(GpuTransition::Ripple, progress)
    }

    /// 从索引创建特效 (循环)
    pub fn from_index(index: usize, progress: f32) -> Self {
        Self::new(GpuTransition::from_index(index), progress)
    }
}

impl Default for GpuBlendEffect {
    fn default() -> Self {
        Self::new(GpuTransition::Squares, 0.0)
    }
}

// ============================================================================
// CPU Buffer Effects (字符级别)
// ============================================================================

/// Effect parameters passed to each effect
#[derive(Clone, Debug)]
pub struct EffectParams {
    /// Progress/time value (0.0 - 1.0 for transitions, or absolute time)
    pub time: f32,
    /// Stage/frame counter for animation
    pub stage: usize,
    /// Random seed for reproducible effects
    pub seed: u32,
    /// Effect intensity multiplier (0.0 - 1.0)
    pub intensity: f32,
}

impl EffectParams {
    /// Create new effect params with time and stage
    pub fn new(time: f32, stage: usize) -> Self {
        Self {
            time,
            stage,
            seed: 0,
            intensity: 1.0,
        }
    }

    /// Set random seed
    pub fn with_seed(mut self, seed: u32) -> Self {
        self.seed = seed;
        self
    }

    /// Set intensity
    pub fn with_intensity(mut self, intensity: f32) -> Self {
        self.intensity = intensity.clamp(0.0, 1.0);
        self
    }
}

impl Default for EffectParams {
    fn default() -> Self {
        Self::new(0.0, 0)
    }
}

/// Trait for CPU-based buffer effects
///
/// Implement this trait to create custom visual effects that operate
/// on Buffer contents at the cell level.
pub trait BufferEffect: Send + Sync {
    /// Apply the effect from source buffer to destination buffer
    ///
    /// # Parameters
    /// - `src`: Source buffer (read-only)
    /// - `dst`: Destination buffer (will be modified)
    /// - `params`: Effect parameters (time, stage, intensity, etc.)
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams);

    /// Get effect name for debugging
    fn name(&self) -> &'static str;
}

// ============================================================================
// Distortion Effects
// ============================================================================

/// Apply a distortion function to remap buffer coordinates
///
/// This is a helper function used by distortion-based effects.
/// The distortion_fn takes normalized UV coordinates (0-1) and returns
/// new UV coordinates for sampling.
pub fn apply_distortion<F>(src: &Buffer, dst: &mut Buffer, distortion_fn: F)
where
    F: Fn(f32, f32) -> (f32, f32),
{
    let width = src.area.width as i32;
    let height = src.area.height as i32;

    for y in 0..height {
        for x in 0..width {
            let u = x as f32 / width as f32;
            let v = y as f32 / height as f32;

            let (du, dv) = distortion_fn(u, v);

            let src_x = (du * width as f32).round() as i32;
            let src_y = (dv * height as f32).round() as i32;

            let src_x = src_x.clamp(0, width - 1);
            let src_y = src_y.clamp(0, height - 1);

            let src_index = (src_y * width + src_x) as usize;
            let dest_index = (y * width + x) as usize;

            if let (Some(src_cell), Some(dest_cell)) = (
                src.content.get(src_index),
                dst.content.get_mut(dest_index),
            ) {
                *dest_cell = src_cell.clone();
            }
        }
    }
}

/// Wave distortion effect - creates horizontal wave patterns
///
/// ```text
/// Before:          After:
/// ┌──────────┐    ┌──────────┐
/// │ AAAAAAAA │    │  AAAAAAAA│
/// │ BBBBBBBB │    │BBBBBBBB  │
/// │ CCCCCCCC │    │  CCCCCCCC│
/// │ DDDDDDDD │    │DDDDDDDD  │
/// └──────────┘    └──────────┘
/// ```
#[derive(Clone, Debug)]
pub struct WaveEffect {
    /// Wave amplitude (0.0 - 0.5, typical: 0.03)
    pub amplitude: f32,
    /// Wave frequency (typical: 10.0 - 20.0)
    pub frequency: f32,
}

impl WaveEffect {
    pub fn new(amplitude: f32, frequency: f32) -> Self {
        Self { amplitude, frequency }
    }
}

impl BufferEffect for WaveEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        let time = params.time;
        let amp = self.amplitude * params.intensity;
        let freq = self.frequency;

        apply_distortion(src, dst, |u, v| {
            let offset_x = u + amp * (freq * v + time).sin();
            (offset_x, v)
        });
    }

    fn name(&self) -> &'static str {
        "WaveEffect"
    }
}

/// Ripple distortion effect - creates circular ripple from center
///
/// ```text
/// Before:          After:
/// ┌──────────┐    ┌──────────┐
/// │ XXXXXXXX │    │ XX    XX │
/// │ XXXXXXXX │    │X  XXXX  X│
/// │ XXXXXXXX │    │X  XXXX  X│
/// │ XXXXXXXX │    │ XX    XX │
/// └──────────┘    └──────────┘
/// ```
#[derive(Clone, Debug)]
pub struct RippleEffect {
    /// Ripple amplitude (0.0 - 0.2, typical: 0.05)
    pub amplitude: f32,
    /// Ripple frequency (typical: 5.0 - 15.0)
    pub frequency: f32,
    /// Center X (0.0 - 1.0, default: 0.5)
    pub center_x: f32,
    /// Center Y (0.0 - 1.0, default: 0.5)
    pub center_y: f32,
}

impl RippleEffect {
    pub fn new(amplitude: f32, frequency: f32) -> Self {
        Self {
            amplitude,
            frequency,
            center_x: 0.5,
            center_y: 0.5,
        }
    }

    pub fn with_center(mut self, cx: f32, cy: f32) -> Self {
        self.center_x = cx;
        self.center_y = cy;
        self
    }
}

impl BufferEffect for RippleEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        let time = params.time;
        let amp = self.amplitude * params.intensity;
        let freq = self.frequency;
        let cx = self.center_x;
        let cy = self.center_y;

        apply_distortion(src, dst, |u, v| {
            let dx = u - cx;
            let dy = v - cy;
            let distance = (dx * dx + dy * dy).sqrt();

            if distance < 0.001 {
                return (u, v);
            }

            let offset = amp * (freq * distance - time).sin();
            let du = u + (dx / distance) * offset;
            let dv = v + (dy / distance) * offset;
            (du, dv)
        });
    }

    fn name(&self) -> &'static str {
        "RippleEffect"
    }
}

/// Swirl distortion effect - rotates pixels around center
#[derive(Clone, Debug)]
pub struct SwirlEffect {
    /// Swirl strength (radians, typical: 0.5 - 2.0)
    pub strength: f32,
    /// Swirl radius (0.0 - 1.0, default: 0.5)
    pub radius: f32,
    /// Center X (0.0 - 1.0, default: 0.5)
    pub center_x: f32,
    /// Center Y (0.0 - 1.0, default: 0.5)
    pub center_y: f32,
}

impl SwirlEffect {
    pub fn new(strength: f32, radius: f32) -> Self {
        Self {
            strength,
            radius,
            center_x: 0.5,
            center_y: 0.5,
        }
    }
}

impl BufferEffect for SwirlEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        let strength = self.strength * params.intensity;
        let radius = self.radius;
        let cx = self.center_x;
        let cy = self.center_y;

        apply_distortion(src, dst, |u, v| {
            let dx = u - cx;
            let dy = v - cy;
            let distance = (dx * dx + dy * dy).sqrt();

            if distance > radius || distance < 0.001 {
                return (u, v);
            }

            let factor = 1.0 - distance / radius;
            let angle = strength * factor * factor;

            let cos_a = angle.cos();
            let sin_a = angle.sin();

            let new_dx = dx * cos_a - dy * sin_a;
            let new_dy = dx * sin_a + dy * cos_a;

            (cx + new_dx, cy + new_dy)
        });
    }

    fn name(&self) -> &'static str {
        "SwirlEffect"
    }
}

// ============================================================================
// Noise and Overlay Effects
// ============================================================================

/// Random noise effect - adds random symbols to buffer
#[derive(Clone, Debug)]
pub struct NoiseEffect {
    /// Noise density (0.0 - 1.0, percentage of cells affected)
    pub density: f32,
    /// Noise color (None = use random grayscale)
    pub color: Option<Color>,
}

impl NoiseEffect {
    pub fn new(density: f32) -> Self {
        Self {
            density: density.clamp(0.0, 1.0),
            color: None,
        }
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

impl BufferEffect for NoiseEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        // First copy source to destination
        dst.content.clone_from(&src.content);

        let density = self.density * params.intensity;
        let cell_count = dst.content.len();
        let noise_count = (cell_count as f32 * density) as usize;

        // Simple LCG random generator using seed
        let mut rng = params.seed.wrapping_add(params.stage as u32);
        let lcg_next = |r: &mut u32| -> u32 {
            *r = r.wrapping_mul(1103515245).wrapping_add(12345);
            *r
        };

        for _ in 0..noise_count {
            let idx = lcg_next(&mut rng) as usize % cell_count;
            let sym = (lcg_next(&mut rng) % 255) as u8;

            let color = self.color.unwrap_or_else(|| {
                let gray = 100 + (lcg_next(&mut rng) % 100) as u8;
                Color::Rgba(gray, gray, gray, 200)
            });

            if let Some(cell) = dst.content.get_mut(idx) {
                cell.set_symbol(&cellsym(sym)).set_fg(color);
            }
        }
    }

    fn name(&self) -> &'static str {
        "NoiseEffect"
    }
}

/// Fade effect - adjusts alpha of all cells
#[derive(Clone, Debug)]
pub struct FadeEffect {
    /// Target alpha (0 = transparent, 255 = opaque)
    pub target_alpha: u8,
}

impl FadeEffect {
    pub fn new(alpha: u8) -> Self {
        Self { target_alpha: alpha }
    }

    /// Create fade-in effect (transparent to opaque based on params.time)
    pub fn fade_in() -> Self {
        Self { target_alpha: 255 }
    }

    /// Create fade-out effect (opaque to transparent based on params.time)
    pub fn fade_out() -> Self {
        Self { target_alpha: 0 }
    }
}

impl BufferEffect for FadeEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        dst.content.clone_from(&src.content);

        let alpha = ((self.target_alpha as f32) * params.intensity) as u8;

        for cell in dst.content.iter_mut() {
            // Modify foreground color alpha
            if let Color::Rgba(r, g, b, _) = cell.fg {
                cell.fg = Color::Rgba(r, g, b, alpha);
            }
        }
    }

    fn name(&self) -> &'static str {
        "FadeEffect"
    }
}

// ============================================================================
// Pixelation and Blur Effects
// ============================================================================

/// Pixelate effect - creates mosaic/blocky appearance
#[derive(Clone, Debug)]
pub struct PixelateEffect {
    /// Block size (1 = no effect, larger = more pixelated)
    pub block_size: u16,
}

impl PixelateEffect {
    pub fn new(block_size: u16) -> Self {
        Self {
            block_size: block_size.max(1),
        }
    }
}

impl BufferEffect for PixelateEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        let width = src.area.width as usize;
        let height = src.area.height as usize;
        let block = (self.block_size as f32 * params.intensity).max(1.0) as usize;

        dst.content.clone_from(&src.content);

        for by in (0..height).step_by(block) {
            for bx in (0..width).step_by(block) {
                // Sample from center of block
                let sample_x = (bx + block / 2).min(width - 1);
                let sample_y = (by + block / 2).min(height - 1);
                let sample_idx = sample_y * width + sample_x;

                if let Some(sample_cell) = src.content.get(sample_idx) {
                    // Fill block with sampled cell
                    for dy in 0..block {
                        for dx in 0..block {
                            let x = bx + dx;
                            let y = by + dy;
                            if x < width && y < height {
                                let idx = y * width + x;
                                if let Some(cell) = dst.content.get_mut(idx) {
                                    *cell = sample_cell.clone();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        "PixelateEffect"
    }
}

/// Simple box blur effect
#[derive(Clone, Debug)]
pub struct BlurEffect {
    /// Blur radius (1 = 3x3, 2 = 5x5, etc.)
    pub radius: u16,
}

impl BlurEffect {
    pub fn new(radius: u16) -> Self {
        Self {
            radius: radius.max(1),
        }
    }
}

impl BufferEffect for BlurEffect {
    fn apply(&self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        let width = src.area.width as i32;
        let height = src.area.height as i32;
        let radius = (self.radius as f32 * params.intensity).max(1.0) as i32;

        dst.content.clone_from(&src.content);

        for y in 0..height {
            for x in 0..width {
                // For character-based blur, we just sample from a random neighbor
                // within the radius (true blur would need color averaging)
                let offset_x = ((x + radius / 2) % (radius * 2 + 1)) - radius;
                let offset_y = ((y + radius / 2) % (radius * 2 + 1)) - radius;

                let sample_x = (x + offset_x).clamp(0, width - 1);
                let sample_y = (y + offset_y).clamp(0, height - 1);

                let src_idx = (sample_y * width + sample_x) as usize;
                let dst_idx = (y * width + x) as usize;

                if let (Some(src_cell), Some(dst_cell)) = (
                    src.content.get(src_idx),
                    dst.content.get_mut(dst_idx),
                ) {
                    *dst_cell = src_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        "BlurEffect"
    }
}

// ============================================================================
// Effect Chain
// ============================================================================

/// Chain multiple effects together
///
/// Effects are applied in order, with each effect's output
/// becoming the next effect's input.
pub struct EffectChain {
    effects: Vec<Box<dyn BufferEffect>>,
    /// Intermediate buffer for chaining (reused to avoid allocation)
    temp_buffer: Option<Buffer>,
}

impl EffectChain {
    pub fn new() -> Self {
        Self {
            effects: Vec::new(),
            temp_buffer: None,
        }
    }

    /// Add an effect to the chain
    pub fn add(&mut self, effect: Box<dyn BufferEffect>) -> &mut Self {
        self.effects.push(effect);
        self
    }

    /// Clear all effects
    pub fn clear(&mut self) {
        self.effects.clear();
    }

    /// Get number of effects in chain
    pub fn len(&self) -> usize {
        self.effects.len()
    }

    /// Check if chain is empty
    pub fn is_empty(&self) -> bool {
        self.effects.is_empty()
    }

    /// Apply all effects in sequence
    pub fn apply(&mut self, src: &Buffer, dst: &mut Buffer, params: &EffectParams) {
        if self.effects.is_empty() {
            dst.content.clone_from(&src.content);
            return;
        }

        if self.effects.len() == 1 {
            self.effects[0].apply(src, dst, params);
            return;
        }

        // Initialize temp buffer if needed
        if self.temp_buffer.is_none() || self.temp_buffer.as_ref().unwrap().area != src.area {
            self.temp_buffer = Some(src.clone());
        }

        let temp = self.temp_buffer.as_mut().unwrap();

        // Apply first effect: src -> temp
        self.effects[0].apply(src, temp, params);

        // Apply middle effects: temp -> dst -> temp (ping-pong)
        for i in 1..self.effects.len() - 1 {
            if i % 2 == 1 {
                self.effects[i].apply(temp, dst, params);
            } else {
                self.effects[i].apply(dst, temp, params);
            }
        }

        // Apply last effect to dst
        let last_idx = self.effects.len() - 1;
        if last_idx % 2 == 1 {
            // Last intermediate result is in temp
            self.effects[last_idx].apply(temp, dst, params);
        } else {
            // Last intermediate result is in dst, need to use temp
            temp.content.clone_from(&dst.content);
            self.effects[last_idx].apply(temp, dst, params);
        }
    }
}

impl Default for EffectChain {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Preset Effect Chains
// ============================================================================

/// Create a dissolve transition effect chain
pub fn dissolve_chain(noise_density: f32) -> EffectChain {
    let mut chain = EffectChain::new();
    chain.add(Box::new(NoiseEffect::new(noise_density)));
    chain
}

/// Create a wave + ripple distortion effect chain
pub fn distortion_chain(wave_amp: f32, ripple_amp: f32) -> EffectChain {
    let mut chain = EffectChain::new();
    chain.add(Box::new(WaveEffect::new(wave_amp, 15.0)));
    chain.add(Box::new(RippleEffect::new(ripple_amp, 10.0)));
    chain
}

/// Create a glitch effect chain (pixelate + noise + wave)
pub fn glitch_chain(intensity: f32) -> EffectChain {
    let mut chain = EffectChain::new();
    chain.add(Box::new(PixelateEffect::new((intensity * 4.0) as u16 + 1)));
    chain.add(Box::new(WaveEffect::new(intensity * 0.1, 20.0)));
    chain.add(Box::new(NoiseEffect::new(intensity * 0.2)));
    chain
}

// ============================================================================
// Buffer Transitions (双Buffer混合,字符级别页面转场)
// ============================================================================

/// 字符级页面转场特效 trait
///
/// 与 BufferEffect 不同,BufferTransition 接受两个源 Buffer (from/to),
/// 根据 progress 将它们混合到目标 Buffer。
///
/// # 工作原理
/// ```text
/// ┌─────────────┐     ┌─────────────┐
/// │ from Buffer │     │  to Buffer  │
/// │  (页面 A)   │     │  (页面 B)   │
/// └──────┬──────┘     └──────┬──────┘
///        │                   │
///        └─────────┬─────────┘
//////        ┌─────────────────────┐
///        │  BufferTransition   │  ← progress (0.0~1.0)
///        │   (字符级混合)       │
///        └──────────┬──────────┘
//////           ┌─────────────┐
///           │  dst Buffer │
///           └─────────────┘
/// ```
///
/// # Example
/// ```ignore
/// let wipe = WipeTransition::left();
/// wipe.transition(&page_a, &page_b, &mut output, 0.5);
/// // output 左半部分是 page_b,右半部分是 page_a
/// ```
pub trait BufferTransition: Send + Sync {
    /// 执行页面转场
    ///
    /// # Parameters
    /// - `from`: 起始页面 Buffer
    /// - `to`: 目标页面 Buffer
    /// - `dst`: 输出 Buffer
    /// - `progress`: 转场进度 (0.0 = 全部显示from, 1.0 = 全部显示to)
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32);

    /// 获取转场名称
    fn name(&self) -> &'static str;
}

/// 转场方向
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WipeDirection {
    Left,
    Right,
    Up,
    Down,
}

/// 擦除转场 - 从一个方向逐渐显示新页面
///
/// ```text
/// WipeLeft (progress=0.3):
/// ┌──────────────────────┐
/// │BBBBBBB│AAAAAAAAAAAAAA│  ← 左30%是to,右70%是from
/// └──────────────────────┘
///
/// WipeDown (progress=0.5):
/// ┌──────────────────────┐
/// │BBBBBBBBBBBBBBBBBBBBBB│  ← 上50%是to
/// │BBBBBBBBBBBBBBBBBBBBBB│
/// │AAAAAAAAAAAAAAAAAAAAAA│  ← 下50%是from
/// │AAAAAAAAAAAAAAAAAAAAAA│
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct WipeTransition {
    pub direction: WipeDirection,
}

impl WipeTransition {
    pub fn new(direction: WipeDirection) -> Self {
        Self { direction }
    }

    pub fn left() -> Self {
        Self::new(WipeDirection::Left)
    }

    pub fn right() -> Self {
        Self::new(WipeDirection::Right)
    }

    pub fn up() -> Self {
        Self::new(WipeDirection::Up)
    }

    pub fn down() -> Self {
        Self::new(WipeDirection::Down)
    }
}

impl BufferTransition for WipeTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let width = from.area.width as usize;
        let height = from.area.height as usize;
        let progress = progress.clamp(0.0, 1.0);

        for y in 0..height {
            for x in 0..width {
                let idx = y * width + x;

                // 判断当前位置应该显示 from 还是 to
                let show_to = match self.direction {
                    WipeDirection::Left => (x as f32) < (width as f32 * progress),
                    WipeDirection::Right => (x as f32) >= (width as f32 * (1.0 - progress)),
                    WipeDirection::Up => (y as f32) < (height as f32 * progress),
                    WipeDirection::Down => (y as f32) >= (height as f32 * (1.0 - progress)),
                };

                let src = if show_to { to } else { from };
                if let (Some(src_cell), Some(dst_cell)) = (
                    src.content.get(idx),
                    dst.content.get_mut(idx),
                ) {
                    *dst_cell = src_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        match self.direction {
            WipeDirection::Left => "WipeLeft",
            WipeDirection::Right => "WipeRight",
            WipeDirection::Up => "WipeUp",
            WipeDirection::Down => "WipeDown",
        }
    }
}

/// 溶解转场 - 随机位置逐个替换字符
///
/// ```text
/// progress=0.3:
/// ┌──────────────────────┐
/// │A B A A B A A A B A A │  ← 约30%的位置显示to(B)
/// │A A B A A A B A A B A │
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct DissolveTransition {
    /// 随机种子
    pub seed: u32,
}

impl DissolveTransition {
    pub fn new(seed: u32) -> Self {
        Self { seed }
    }
}

impl Default for DissolveTransition {
    fn default() -> Self {
        Self { seed: 12345 }
    }
}

impl BufferTransition for DissolveTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let cell_count = from.content.len();
        let progress = progress.clamp(0.0, 1.0);

        // 生成随机顺序 (使用确定性shuffle)
        let mut indices: Vec<usize> = (0..cell_count).collect();

        // Fisher-Yates shuffle with LCG
        let mut rng = self.seed;
        let lcg_next = |r: &mut u32| -> u32 {
            *r = r.wrapping_mul(1103515245).wrapping_add(12345);
            *r
        };

        for i in (1..cell_count).rev() {
            let j = lcg_next(&mut rng) as usize % (i + 1);
            indices.swap(i, j);
        }

        // 根据 progress 决定多少个位置显示 to
        let reveal_count = (cell_count as f32 * progress) as usize;

        // 先复制 from 到 dst
        dst.content.clone_from(&from.content);

        // 将前 reveal_count 个随机位置替换为 to
        for &idx in indices.iter().take(reveal_count) {
            if let (Some(to_cell), Some(dst_cell)) = (
                to.content.get(idx),
                dst.content.get_mut(idx),
            ) {
                *dst_cell = to_cell.clone();
            }
        }
    }

    fn name(&self) -> &'static str {
        "Dissolve"
    }
}

/// 打字机转场 - 逐字符从左到右、从上到下显示
///
/// ```text
/// progress=0.3 (假设总共20个字符,显示6个):
/// ┌──────────────────────┐
/// │BBBBBB AAAAAAAAAAAAA │  ← 前6个字符是to
/// │AAAAAAAAAAAAAAAAAAAAAA│
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct TypewriterTransition {
    /// 是否显示光标
    pub show_cursor: bool,
    /// 光标字符
    pub cursor_char: char,
}

impl TypewriterTransition {
    pub fn new() -> Self {
        Self {
            show_cursor: true,
            cursor_char: '',
        }
    }

    pub fn without_cursor() -> Self {
        Self {
            show_cursor: false,
            cursor_char: '',
        }
    }

    pub fn with_cursor(cursor: char) -> Self {
        Self {
            show_cursor: true,
            cursor_char: cursor,
        }
    }
}

impl Default for TypewriterTransition {
    fn default() -> Self {
        Self::new()
    }
}

impl BufferTransition for TypewriterTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let cell_count = from.content.len();
        let progress = progress.clamp(0.0, 1.0);
        let reveal_count = (cell_count as f32 * progress) as usize;

        for (idx, dst_cell) in dst.content.iter_mut().enumerate() {
            if idx < reveal_count {
                // 显示 to
                if let Some(to_cell) = to.content.get(idx) {
                    *dst_cell = to_cell.clone();
                }
            } else if idx == reveal_count && self.show_cursor && progress < 1.0 {
                // 光标位置
                if let Some(from_cell) = from.content.get(idx) {
                    *dst_cell = from_cell.clone();
                    dst_cell.set_symbol(&self.cursor_char.to_string());
                }
            } else {
                // 显示 from
                if let Some(from_cell) = from.content.get(idx) {
                    *dst_cell = from_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        "Typewriter"
    }
}

/// 百叶窗转场方向
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlindsDirection {
    Horizontal,
    Vertical,
}

/// 百叶窗转场 - 像百叶窗一样逐条显示
///
/// ```text
/// Horizontal blinds (progress=0.5, slices=4):
/// ┌──────────────────────┐
/// │BBBBBBBBBBBBBBBBBBBBBB│  ← 第1条: to
/// │AAAAAAAAAAAAAAAAAAAAAA│  ← 第2条: from (未到)
/// │BBBBBBBBBBBBBBBBBBBBBB│  ← 第3条: to
/// │AAAAAAAAAAAAAAAAAAAAAA│  ← 第4条: from (未到)
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct BlindsTransition {
    pub direction: BlindsDirection,
    /// 百叶窗条数
    pub slices: usize,
}

impl BlindsTransition {
    pub fn new(direction: BlindsDirection, slices: usize) -> Self {
        Self {
            direction,
            slices: slices.max(2),
        }
    }

    pub fn horizontal(slices: usize) -> Self {
        Self::new(BlindsDirection::Horizontal, slices)
    }

    pub fn vertical(slices: usize) -> Self {
        Self::new(BlindsDirection::Vertical, slices)
    }
}

impl BufferTransition for BlindsTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let width = from.area.width as usize;
        let height = from.area.height as usize;
        let progress = progress.clamp(0.0, 1.0);

        let (_total_size, slice_size) = match self.direction {
            BlindsDirection::Horizontal => (height, height.div_ceil(self.slices)),
            BlindsDirection::Vertical => (width, width.div_ceil(self.slices)),
        };

        for y in 0..height {
            for x in 0..width {
                let idx = y * width + x;

                // 确定当前位置在哪个 slice
                let pos = match self.direction {
                    BlindsDirection::Horizontal => y,
                    BlindsDirection::Vertical => x,
                };
                let slice_idx = pos / slice_size;
                let pos_in_slice = pos % slice_size;

                // 每个 slice 内部的进度
                let slice_progress = (progress * self.slices as f32 - slice_idx as f32).clamp(0.0, 1.0);
                let reveal_in_slice = (slice_size as f32 * slice_progress) as usize;

                let show_to = pos_in_slice < reveal_in_slice;

                let src = if show_to { to } else { from };
                if let (Some(src_cell), Some(dst_cell)) = (
                    src.content.get(idx),
                    dst.content.get_mut(idx),
                ) {
                    *dst_cell = src_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        match self.direction {
            BlindsDirection::Horizontal => "BlindsHorizontal",
            BlindsDirection::Vertical => "BlindsVertical",
        }
    }
}

/// 棋盘格转场 - 像棋盘一样交替显示
///
/// ```text
/// progress=0.5 (block_size=2):
/// ┌──────────────────────┐
/// │BB  BB  BB  BB  BB   │  ← 交替的方块
/// │BB  BB  BB  BB  BB   │
/// │  AA  AA  AA  AA  AA │
/// │  AA  AA  AA  AA  AA │
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct CheckerboardTransition {
    /// 方块大小
    pub block_size: usize,
}

impl CheckerboardTransition {
    pub fn new(block_size: usize) -> Self {
        Self {
            block_size: block_size.max(1),
        }
    }
}

impl Default for CheckerboardTransition {
    fn default() -> Self {
        Self { block_size: 2 }
    }
}

impl BufferTransition for CheckerboardTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let width = from.area.width as usize;
        let height = from.area.height as usize;
        let progress = progress.clamp(0.0, 1.0);
        let block = self.block_size;

        // 分两阶段:
        // 0.0-0.5: 奇数格子显示 to
        // 0.5-1.0: 偶数格子也显示 to
        let phase1 = (progress * 2.0).min(1.0);
        let phase2 = ((progress - 0.5) * 2.0).clamp(0.0, 1.0);

        for y in 0..height {
            for x in 0..width {
                let idx = y * width + x;

                let block_x = x / block;
                let block_y = y / block;
                let is_odd_block = (block_x + block_y) % 2 == 1;

                let show_to = if is_odd_block {
                    phase1 > 0.5
                } else {
                    phase2 > 0.5
                };

                let src = if show_to { to } else { from };
                if let (Some(src_cell), Some(dst_cell)) = (
                    src.content.get(idx),
                    dst.content.get_mut(idx),
                ) {
                    *dst_cell = src_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        "Checkerboard"
    }
}

/// 滑动转场 - 两个页面同时移动
///
/// ```text
/// SlideLeft (progress=0.3):
/// ┌──────────────────────┐
/// │AAAAAAAAAAAAAAA│BBBBBB│  ← A向左滑出,B从右滑入
/// └──────────────────────┘
/// ```
#[derive(Clone, Debug)]
pub struct SlideTransition {
    pub direction: WipeDirection,
}

impl SlideTransition {
    pub fn new(direction: WipeDirection) -> Self {
        Self { direction }
    }

    pub fn left() -> Self {
        Self::new(WipeDirection::Left)
    }

    pub fn right() -> Self {
        Self::new(WipeDirection::Right)
    }

    pub fn up() -> Self {
        Self::new(WipeDirection::Up)
    }

    pub fn down() -> Self {
        Self::new(WipeDirection::Down)
    }
}

impl BufferTransition for SlideTransition {
    fn transition(&self, from: &Buffer, to: &Buffer, dst: &mut Buffer, progress: f32) {
        let width = from.area.width as usize;
        let height = from.area.height as usize;
        let progress = progress.clamp(0.0, 1.0);

        for y in 0..height {
            for x in 0..width {
                let idx = y * width + x;

                // 计算源坐标
                let (src_x, src_y, use_to) = match self.direction {
                    WipeDirection::Left => {
                        let offset = (width as f32 * progress) as i32;
                        let new_x = x as i32 + offset;
                        if new_x < width as i32 {
                            (new_x as usize, y, false) // 从 from
                        } else {
                            ((new_x - width as i32) as usize, y, true) // 从 to
                        }
                    }
                    WipeDirection::Right => {
                        let offset = (width as f32 * progress) as i32;
                        let new_x = x as i32 - offset;
                        if new_x >= 0 {
                            (new_x as usize, y, false) // 从 from
                        } else {
                            ((width as i32 + new_x) as usize, y, true) // 从 to
                        }
                    }
                    WipeDirection::Up => {
                        let offset = (height as f32 * progress) as i32;
                        let new_y = y as i32 + offset;
                        if new_y < height as i32 {
                            (x, new_y as usize, false) // 从 from
                        } else {
                            (x, (new_y - height as i32) as usize, true) // 从 to
                        }
                    }
                    WipeDirection::Down => {
                        let offset = (height as f32 * progress) as i32;
                        let new_y = y as i32 - offset;
                        if new_y >= 0 {
                            (x, new_y as usize, false) // 从 from
                        } else {
                            (x, (height as i32 + new_y) as usize, true) // 从 to
                        }
                    }
                };

                let src = if use_to { to } else { from };
                let src_idx = src_y * width + src_x;

                if let (Some(src_cell), Some(dst_cell)) = (
                    src.content.get(src_idx),
                    dst.content.get_mut(idx),
                ) {
                    *dst_cell = src_cell.clone();
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        match self.direction {
            WipeDirection::Left => "SlideLeft",
            WipeDirection::Right => "SlideRight",
            WipeDirection::Up => "SlideUp",
            WipeDirection::Down => "SlideDown",
        }
    }
}

/// 转场类型枚举 (便于统一管理)
#[derive(Clone, Debug)]
pub enum TransitionType {
    WipeLeft,
    WipeRight,
    WipeUp,
    WipeDown,
    SlideLeft,
    SlideRight,
    SlideUp,
    SlideDown,
    Dissolve(u32),
    Typewriter,
    BlindsHorizontal(usize),
    BlindsVertical(usize),
    Checkerboard(usize),
}

impl TransitionType {
    /// 创建对应的 BufferTransition 实例
    pub fn create(&self) -> Box<dyn BufferTransition> {
        match self {
            TransitionType::WipeLeft => Box::new(WipeTransition::left()),
            TransitionType::WipeRight => Box::new(WipeTransition::right()),
            TransitionType::WipeUp => Box::new(WipeTransition::up()),
            TransitionType::WipeDown => Box::new(WipeTransition::down()),
            TransitionType::SlideLeft => Box::new(SlideTransition::left()),
            TransitionType::SlideRight => Box::new(SlideTransition::right()),
            TransitionType::SlideUp => Box::new(SlideTransition::up()),
            TransitionType::SlideDown => Box::new(SlideTransition::down()),
            TransitionType::Dissolve(seed) => Box::new(DissolveTransition::new(*seed)),
            TransitionType::Typewriter => Box::new(TypewriterTransition::new()),
            TransitionType::BlindsHorizontal(slices) => Box::new(BlindsTransition::horizontal(*slices)),
            TransitionType::BlindsVertical(slices) => Box::new(BlindsTransition::vertical(*slices)),
            TransitionType::Checkerboard(size) => Box::new(CheckerboardTransition::new(*size)),
        }
    }

    /// 获取所有转场类型
    pub fn all() -> Vec<TransitionType> {
        vec![
            TransitionType::WipeLeft,
            TransitionType::WipeRight,
            TransitionType::WipeUp,
            TransitionType::WipeDown,
            TransitionType::SlideLeft,
            TransitionType::SlideRight,
            TransitionType::SlideUp,
            TransitionType::SlideDown,
            TransitionType::Dissolve(12345),
            TransitionType::Typewriter,
            TransitionType::BlindsHorizontal(4),
            TransitionType::BlindsVertical(4),
            TransitionType::Checkerboard(2),
        ]
    }

    /// 获取名称
    pub fn name(&self) -> &'static str {
        match self {
            TransitionType::WipeLeft => "WipeLeft",
            TransitionType::WipeRight => "WipeRight",
            TransitionType::WipeUp => "WipeUp",
            TransitionType::WipeDown => "WipeDown",
            TransitionType::SlideLeft => "SlideLeft",
            TransitionType::SlideRight => "SlideRight",
            TransitionType::SlideUp => "SlideUp",
            TransitionType::SlideDown => "SlideDown",
            TransitionType::Dissolve(_) => "Dissolve",
            TransitionType::Typewriter => "Typewriter",
            TransitionType::BlindsHorizontal(_) => "BlindsH",
            TransitionType::BlindsVertical(_) => "BlindsV",
            TransitionType::Checkerboard(_) => "Checkerboard",
        }
    }
}