alice-lol 0.4.2

ALICE-LOL: Law-Oriented Language — proc_macro + runtime DSL compiling to SdfNode (GLSL/WGSL/HLSL transpile), print export (STL/3MF/OBJ/FBX), law checker, laser pattern generator, and optional LLM Guided Generation bridge.
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
//! レーザー彫刻向け2Dパターン生成
//!
//! SDF距離場を使わず、2D幾何学パターンをSVGパスデータとして生成する。
//! LOL DSL → `LaserPattern` → SVG のパイプライン。
#![allow(
    clippy::disallowed_macros,
    reason = "raw-helper: this module calls the platform f32/f64 max/min via crate::raw_minmax::raw_minmax_here!() at sites proven safe by nonzero-const:/both-abs:/int-cast: reasoning, see scripts/raw_minmax_manifest.toml"
)]

crate::raw_minmax::raw_minmax_here!(max_f64);

use std::f64::consts::PI;
use std::fmt::Write;

// ──────────────────────────────────────────────────────
//  基本型
// ──────────────────────────────────────────────────────

/// 2Dレーザー要素
#[derive(Debug, Clone)]
pub enum LaserElement {
    /// 直線セグメント (x1, y1, x2, y2)
    Line(f64, f64, f64, f64),
    /// 円 (cx, cy, radius)
    Circle(f64, f64, f64),
    /// ドット (cx, cy) — 単一レーザーパルス
    Dot(f64, f64),
    /// ポリライン (連続する点列)
    Polyline(Vec<(f64, f64)>),
}

/// 2Dバウンディング矩形 (x, y, width, height)
#[derive(Debug, Clone, Copy)]
pub struct Bounds {
    pub x: f64,
    pub y: f64,
    pub w: f64,
    pub h: f64,
}

impl Bounds {
    #[must_use]
    pub const fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
        Self { x, y, w, h }
    }

    /// 点がバウンディング内か
    #[must_use]
    pub fn contains(&self, px: f64, py: f64) -> bool {
        px >= self.x && px <= self.x + self.w && py >= self.y && py <= self.y + self.h
    }

    /// 中心座標
    #[must_use]
    // const fn では f64::mul_add が 1.92 以下で未安定 (下流の非公開 crate は 1.92 pin、2026-09-15 red)
    #[allow(clippy::suboptimal_flops)]
    pub const fn center(&self) -> (f64, f64) {
        (self.x + self.w * 0.5, self.y + self.h * 0.5)
    }
}

// ──────────────────────────────────────────────────────
//  Phase A: hatch / crosshatch / density_hatch
// ──────────────────────────────────────────────────────

/// 線形ハッチングパターン生成
///
/// `angle`: 度数法(0=水平、90=垂直、45=斜め)
/// `spacing`: 線間隔 (mm)
/// `bounds`: クリッピング矩形
///
/// 矩形内を平行線で埋める。角度は反時計回り。
#[must_use]
pub fn hatch(angle_deg: f64, spacing: f64, bounds: &Bounds) -> Vec<LaserElement> {
    if spacing <= 0.0 {
        return Vec::new();
    }

    let angle = angle_deg.to_radians();
    let cos_a = alice_det_math::cos64(angle);
    let sin_a = alice_det_math::sin64(angle);

    // 矩形の4頂点
    let corners = [
        (bounds.x, bounds.y),
        (bounds.x + bounds.w, bounds.y),
        (bounds.x + bounds.w, bounds.y + bounds.h),
        (bounds.x, bounds.y + bounds.h),
    ];

    // 法線方向への各頂点の射影距離
    let projections: Vec<f64> = corners
        .iter()
        .map(|&(cx, cy)| (-sin_a).mul_add(cx, cos_a * cy))
        .collect();
    let proj_min = projections
        .iter()
        .copied()
        .fold(f64::INFINITY, crate::det_math::min64);
    let proj_max = projections
        .iter()
        .copied()
        .fold(f64::NEG_INFINITY, crate::det_math::max64);

    let mut elements = Vec::new();
    let d0 = (proj_min / spacing).ceil() * spacing;
    // 固定間隔なので整数 index で刻む (float の累積加算より誤差が溜まらない)
    let line_count = cell_count(proj_max - d0, spacing) + 1;

    for i in 0..line_count {
        let d = usize_f64(i).mul_add(spacing, d0);
        // d = -sin_a * x + cos_a * y の直線と矩形の交点を求める
        if let Some((x1, y1, x2, y2)) = clip_line_to_rect(cos_a, sin_a, d, bounds) {
            elements.push(LaserElement::Line(x1, y1, x2, y2));
        }
    }

    elements
}

/// クロスハッチングパターン(0° + 90°)
///
/// `spacing`: 線間隔 (mm)
/// `bounds`: クリッピング矩形
#[must_use]
pub fn crosshatch(spacing: f64, bounds: &Bounds) -> Vec<LaserElement> {
    let mut elements = hatch(0.0, spacing, bounds);
    elements.extend(hatch(90.0, spacing, bounds));
    elements
}

/// 可変密度ハッチング
///
/// SDF距離に基づいて線間隔を変調する。中心に近いほど密、端ほど疎。
///
/// `min_spacing`: 最密部の線間隔 (mm)
/// `max_spacing`: 最疎部の線間隔 (mm)
/// `angle_deg`: ハッチ角度(度数法)
/// `bounds`: クリッピング矩形
/// `density_fn`: (x, y) → 0.0..1.0 の密度関数。1.0=最密、0.0=最疎
#[must_use]
#[allow(clippy::while_float)] // 線間隔が密度で変わるので整数 index で刻めない
pub fn density_hatch(
    min_spacing: f64,
    max_spacing: f64,
    angle_deg: f64,
    bounds: &Bounds,
    density_fn: &dyn Fn(f64, f64) -> f64,
) -> Vec<LaserElement> {
    if min_spacing <= 0.0 || max_spacing <= 0.0 {
        return Vec::new();
    }

    let angle = angle_deg.to_radians();
    let cos_a = alice_det_math::cos64(angle);
    let sin_a = alice_det_math::sin64(angle);

    let corners = [
        (bounds.x, bounds.y),
        (bounds.x + bounds.w, bounds.y),
        (bounds.x + bounds.w, bounds.y + bounds.h),
        (bounds.x, bounds.y + bounds.h),
    ];
    let projections: Vec<f64> = corners
        .iter()
        .map(|&(cx, cy)| (-sin_a).mul_add(cx, cos_a * cy))
        .collect();
    let proj_min = projections
        .iter()
        .copied()
        .fold(f64::INFINITY, crate::det_math::min64);
    let proj_max = projections
        .iter()
        .copied()
        .fold(f64::NEG_INFINITY, crate::det_math::max64);

    let mut elements = Vec::new();
    let mut d = proj_min;

    while d <= proj_max {
        if let Some((x1, y1, x2, y2)) = clip_line_to_rect(cos_a, sin_a, d, bounds) {
            elements.push(LaserElement::Line(x1, y1, x2, y2));

            // 次の線までの間隔を、この線の中点の密度で決定
            let mx = f64::midpoint(x1, x2);
            let my = f64::midpoint(y1, y2);
            let density = density_fn(mx, my).clamp(0.0, 1.0);
            let spacing = (max_spacing - min_spacing).mul_add(-density, max_spacing);
            d += spacing;
        } else {
            d += min_spacing;
        }
    }

    elements
}

/// 直線 (`-sin_a * x + cos_a * y = d`) と矩形のクリッピング
///
/// Cohen-Sutherland 的に矩形の4辺との交点を求め、矩形内のセグメントを返す。
fn clip_line_to_rect(
    cos_a: f64,
    sin_a: f64,
    d: f64,
    bounds: &Bounds,
) -> Option<(f64, f64, f64, f64)> {
    let x_min = bounds.x;
    let x_max = bounds.x + bounds.w;
    let y_min = bounds.y;
    let y_max = bounds.y + bounds.h;

    let mut intersections = Vec::with_capacity(4);
    let eps = 1e-12;

    // 上辺 y = y_min: x = (d - cos_a * y_min) / (-sin_a)
    if sin_a.abs() > eps {
        let x = cos_a.mul_add(-y_min, d) / (-sin_a);
        if x >= x_min - eps && x <= x_max + eps {
            intersections.push((x.clamp(x_min, x_max), y_min));
        }
    }
    // 下辺 y = y_max: x = (d - cos_a * y_max) / (-sin_a)
    if sin_a.abs() > eps {
        let x = cos_a.mul_add(-y_max, d) / (-sin_a);
        if x >= x_min - eps && x <= x_max + eps {
            intersections.push((x.clamp(x_min, x_max), y_max));
        }
    }
    // 左辺 x = x_min: y = (d + sin_a * x_min) / cos_a
    if cos_a.abs() > eps {
        let y = sin_a.mul_add(x_min, d) / cos_a;
        if y >= y_min - eps && y <= y_max + eps {
            intersections.push((x_min, y.clamp(y_min, y_max)));
        }
    }
    // 右辺 x = x_max: y = (d + sin_a * x_max) / cos_a
    if cos_a.abs() > eps {
        let y = sin_a.mul_add(x_max, d) / cos_a;
        if y >= y_min - eps && y <= y_max + eps {
            intersections.push((x_max, y.clamp(y_min, y_max)));
        }
    }

    // 重複除去(角の交点で2回ヒットする場合)
    intersections.dedup_by(|a, b| (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps);

    if intersections.len() >= 2 {
        Some((
            intersections[0].0,
            intersections[0].1,
            intersections[1].0,
            intersections[1].1,
        ))
    } else {
        None
    }
}

// ──────────────────────────────────────────────────────
//  Phase B: halftone / dither
// ──────────────────────────────────────────────────────

/// AMハーフトーン(振幅変調)
///
/// 等間隔グリッド上にドットを配置し、ドット半径を輝度で変調する。
///
/// `lpi`: lines per inch(グリッド密度)
/// `max_radius`: 最大ドット半径 (mm)
/// `bounds`: クリッピング矩形
/// `brightness_fn`: (x, y) → 0.0(黒=最大ドット)..1.0(白=ドットなし)
#[must_use]
pub fn halftone(
    lpi: f64,
    max_radius: f64,
    bounds: &Bounds,
    brightness_fn: &dyn Fn(f64, f64) -> f64,
) -> Vec<LaserElement> {
    if lpi <= 0.0 || max_radius <= 0.0 {
        return Vec::new();
    }

    let cell_size = 25.4 / lpi; // mm per cell
    let mut elements = Vec::new();

    let cols = cell_count(bounds.w, cell_size);
    let rows = cell_count(bounds.h, cell_size);

    for row in 0..rows {
        for col in 0..cols {
            let cx = cell_center(col, cell_size, bounds.x);
            let cy = cell_center(row, cell_size, bounds.y);

            if !bounds.contains(cx, cy) {
                continue;
            }

            let brightness = brightness_fn(cx, cy).clamp(0.0, 1.0);
            let radius = max_radius * (1.0 - brightness);

            if radius > 0.01 {
                elements.push(LaserElement::Circle(cx, cy, radius));
            }
        }
    }

    elements
}

/// ディザリングアルゴリズム
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DitherAlgorithm {
    FloydSteinberg,
    Atkinson,
    Stucki,
    Jarvis,
    Bayer4x4,
}

/// ディザリングパターン生成
///
/// 輝度マップをバイナリ(ドット有/無)に変換する。
///
/// `algorithm`: ディザリング手法
/// `dpi`: 解像度
/// `bounds`: 対象領域
/// `brightness_fn`: (x, y) → 0.0(黒)..1.0(白)
#[must_use]
pub fn dither(
    algorithm: DitherAlgorithm,
    dpi: f64,
    bounds: &Bounds,
    brightness_fn: &dyn Fn(f64, f64) -> f64,
) -> Vec<LaserElement> {
    if dpi <= 0.0 {
        return Vec::new();
    }

    let pixel_size = 25.4 / dpi;
    let cols = cell_count(bounds.w, pixel_size).max(1);
    let rows = cell_count(bounds.h, pixel_size).max(1);

    // 輝度マップをサンプリング
    let mut grid: Vec<Vec<f64>> = Vec::with_capacity(rows);
    for row in 0..rows {
        let mut scanline = Vec::with_capacity(cols);
        for col in 0..cols {
            let x = cell_center(col, pixel_size, bounds.x);
            let y = cell_center(row, pixel_size, bounds.y);
            let b = brightness_fn(x, y).clamp(0.0, 1.0);
            scanline.push(b);
        }
        grid.push(scanline);
    }

    match algorithm {
        DitherAlgorithm::Bayer4x4 => dither_ordered(&grid, pixel_size, bounds, cols, rows),
        _ => dither_error_diffusion(algorithm, &mut grid, pixel_size, bounds, cols, rows),
    }
}

/// 誤差拡散ディザリング
fn dither_error_diffusion(
    algorithm: DitherAlgorithm,
    grid: &mut [Vec<f64>],
    pixel_size: f64,
    bounds: &Bounds,
    cols: usize,
    rows: usize,
) -> Vec<LaserElement> {
    // (dx, dy, weight) — 合計が divisor になる
    let (offsets, divisor): (&[(isize, isize, f64)], f64) = match algorithm {
        DitherAlgorithm::FloydSteinberg => {
            (&[(1, 0, 7.0), (-1, 1, 3.0), (0, 1, 5.0), (1, 1, 1.0)], 16.0)
        }
        DitherAlgorithm::Atkinson => (
            &[
                (1, 0, 1.0),
                (2, 0, 1.0),
                (-1, 1, 1.0),
                (0, 1, 1.0),
                (1, 1, 1.0),
                (0, 2, 1.0),
            ],
            8.0, // 6/8 = 75% のみ拡散
        ),
        DitherAlgorithm::Stucki => (
            &[
                (1, 0, 8.0),
                (2, 0, 4.0),
                (-2, 1, 2.0),
                (-1, 1, 4.0),
                (0, 1, 8.0),
                (1, 1, 4.0),
                (2, 1, 2.0),
                (-2, 2, 1.0),
                (-1, 2, 2.0),
                (0, 2, 4.0),
                (1, 2, 2.0),
                (2, 2, 1.0),
            ],
            42.0,
        ),
        DitherAlgorithm::Jarvis => (
            &[
                (1, 0, 7.0),
                (2, 0, 5.0),
                (-2, 1, 3.0),
                (-1, 1, 5.0),
                (0, 1, 7.0),
                (1, 1, 5.0),
                (2, 1, 3.0),
                (-2, 2, 1.0),
                (-1, 2, 3.0),
                (0, 2, 5.0),
                (1, 2, 3.0),
                (2, 2, 1.0),
            ],
            48.0,
        ),
        DitherAlgorithm::Bayer4x4 => unreachable!(),
    };

    let mut dots = Vec::new();

    for y in 0..rows {
        for x in 0..cols {
            let old = grid[y][x];
            let new_val = if old < 0.5 { 0.0 } else { 1.0 };
            let error = old - new_val;

            grid[y][x] = new_val;

            // 誤差拡散
            for &(dx, dy, weight) in offsets {
                // 左端 / 上端で負になる offset は checked_add_signed で None
                let (Some(nx), Some(ny)) = (x.checked_add_signed(dx), y.checked_add_signed(dy))
                else {
                    continue;
                };
                if nx < cols && ny < rows {
                    grid[ny][nx] += error * weight / divisor;
                }
            }

            // 黒ピクセル → ドット
            if new_val < 0.5 {
                let px = cell_center(x, pixel_size, bounds.x);
                let py = cell_center(y, pixel_size, bounds.y);
                dots.push(LaserElement::Dot(px, py));
            }
        }
    }

    dots
}

/// 順序ディザリング (Bayer 4x4)
fn dither_ordered(
    grid: &[Vec<f64>],
    pixel_size: f64,
    bounds: &Bounds,
    cols: usize,
    rows: usize,
) -> Vec<LaserElement> {
    #[rustfmt::skip]
    const BAYER4: [[f64; 4]; 4] = [
        [ 0.0/16.0,  8.0/16.0,  2.0/16.0, 10.0/16.0],
        [12.0/16.0,  4.0/16.0, 14.0/16.0,  6.0/16.0],
        [ 3.0/16.0, 11.0/16.0,  1.0/16.0,  9.0/16.0],
        [15.0/16.0,  7.0/16.0, 13.0/16.0,  5.0/16.0],
    ];

    let mut dots = Vec::new();

    for y in 0..rows {
        for x in 0..cols {
            let threshold = BAYER4[y & 3][x & 3];
            if grid[y][x] < threshold {
                let px = cell_center(x, pixel_size, bounds.x);
                let py = cell_center(y, pixel_size, bounds.y);
                dots.push(LaserElement::Dot(px, py));
            }
        }
    }

    dots
}

// ──────────────────────────────────────────────────────
//  Phase C: 装飾パターン
// ──────────────────────────────────────────────────────

/// ギョッシェ / スピログラフ(ヒポトロコイド曲線)
///
/// `big_r`: 固定円半径
/// `small_r`: 転がり円半径
/// `pen_d`: ペンオフセット
/// `steps`: 描画ステップ数(多いほど滑らか)
/// `bounds`: クリッピング(中心をboundsの中心に配置)
#[must_use]
pub fn guilloche(
    big_r: f64,
    small_r: f64,
    pen_d: f64,
    steps: u32,
    bounds: &Bounds,
) -> Vec<LaserElement> {
    if small_r.abs() < 1e-12 || steps == 0 {
        return Vec::new();
    }

    let (cx, cy) = bounds.center();

    // 完全な1周のためのt範囲を計算
    let t_max = 2.0 * PI * small_r / gcd_f64(big_r, small_r);
    let dt = t_max / f64::from(steps);

    let mut points = Vec::with_capacity(steps as usize + 1);
    for i in 0..=steps {
        let t = f64::from(i) * dt;
        let diff = big_r - small_r;
        let ratio = diff / small_r;
        let x = pen_d.mul_add(
            alice_det_math::cos64(ratio * t),
            diff.mul_add(alice_det_math::cos64(t), cx),
        );
        let y = pen_d.mul_add(
            -alice_det_math::sin64(ratio * t),
            diff.mul_add(alice_det_math::sin64(t), cy),
        );
        points.push((x, y));
    }

    vec![LaserElement::Polyline(points)]
}

/// リサジュー曲線
///
/// `freq_a`: X周波数
/// `freq_b`: Y周波数
/// `delta`: 位相差(ラジアン)
/// `amplitude`: 振幅 (mm)
/// `steps`: 描画ステップ数
/// `bounds`: 中心配置用
#[must_use]
pub fn lissajous(
    freq_a: f64,
    freq_b: f64,
    delta: f64,
    amplitude: f64,
    steps: u32,
    bounds: &Bounds,
) -> Vec<LaserElement> {
    if steps == 0 {
        return Vec::new();
    }

    let (cx, cy) = bounds.center();
    let dt = 2.0 * PI / f64::from(steps);

    let mut points = Vec::with_capacity(steps as usize + 1);
    for i in 0..=steps {
        let t = f64::from(i) * dt;
        let x = amplitude.mul_add(alice_det_math::sin64(freq_a.mul_add(t, delta)), cx);
        let y = amplitude.mul_add(alice_det_math::sin64(freq_b * t), cy);
        points.push((x, y));
    }

    vec![LaserElement::Polyline(points)]
}

/// ローズカーブ(ロドネア曲線)
///
/// `k`: 花弁パラメータ(整数で閉曲線、奇数→k枚、偶数→2k枚)
/// `amplitude`: 振幅 (mm)
/// `steps`: 描画ステップ数
/// `bounds`: 中心配置用
#[must_use]
#[allow(clippy::many_single_char_names)] // rhodonea 標準記法 r = a·cos(kθ)
pub fn rose(k: f64, amplitude: f64, steps: u32, bounds: &Bounds) -> Vec<LaserElement> {
    if steps == 0 {
        return Vec::new();
    }

    let (cx, cy) = bounds.center();
    // k が整数なら 2π で閉じる(奇数)か π で閉じる(偶数として扱う)
    let t_max = 2.0 * PI;
    let dt = t_max / f64::from(steps);

    let mut points = Vec::with_capacity(steps as usize + 1);
    for i in 0..=steps {
        let t = f64::from(i) * dt;
        let r = amplitude * alice_det_math::cos64(k * t);
        let x = cx + r * alice_det_math::cos64(t);
        let y = cy + r * alice_det_math::sin64(t);
        points.push((x, y));
    }

    vec![LaserElement::Polyline(points)]
}

/// フィロタキシス(向日葵螺旋)
///
/// `n`: ドット数
/// `scale`: スケール係数(大きいほど広がる)
/// `bounds`: 中心配置用
#[must_use]
pub fn phyllotaxis(n: u32, scale: f64, bounds: &Bounds) -> Vec<LaserElement> {
    let (cx, cy) = bounds.center();
    let golden_angle = 137.508_f64.to_radians();

    let mut dots = Vec::with_capacity(n as usize);
    for i in 0..n {
        let theta = f64::from(i) * golden_angle;
        let r = scale * f64::from(i).sqrt();
        let x = r.mul_add(alice_det_math::cos64(theta), cx);
        let y = r.mul_add(alice_det_math::sin64(theta), cy);

        if bounds.contains(x, y) {
            dots.push(LaserElement::Dot(x, y));
        }
    }

    dots
}

/// チューリングパターン(Gray-Scottモデル反応拡散)
///
/// `feed`: フィード率 F (0.01-0.08)
/// `kill`: キル率 k (0.04-0.07)
/// `resolution`: グリッド解像度(一辺のセル数)
/// `iterations`: シミュレーションステップ数
/// `bounds`: 出力領域
/// `threshold`: 閾値(v がこの値以上のセルをドットとして出力)
#[must_use]
pub fn turing(
    feed: f64,
    kill: f64,
    resolution: u32,
    iterations: u32,
    bounds: &Bounds,
    threshold: f64,
) -> Vec<LaserElement> {
    let n = resolution as usize;
    if n < 4 {
        return Vec::new();
    }

    let du = 0.16_f64;
    let dv = 0.08_f64;
    let dt = 1.0_f64;

    // U=1, V=0 を初期条件、中央付近にV=0.25の種を複数箇所にまく
    let mut u = vec![vec![1.0_f64; n]; n];
    let mut v = vec![vec![0.0_f64; n]; n];

    // 中央の大きなシード
    let center = n / 2;
    let seed_r = (n / 5).max(2);
    for row in center.saturating_sub(seed_r)..=(center + seed_r).min(n - 1) {
        for col in center.saturating_sub(seed_r)..=(center + seed_r).min(n - 1) {
            u[row][col] = 0.5;
            v[row][col] = 0.25;
        }
    }
    // 四隅にも小さいシードを配置(パターンの伝播を促進)
    let small_r = (n / 8).max(1);
    for &(sy, sx) in &[
        (n / 4, n / 4),
        (n / 4, 3 * n / 4),
        (3 * n / 4, n / 4),
        (3 * n / 4, 3 * n / 4),
    ] {
        for row in sy.saturating_sub(small_r)..=(sy + small_r).min(n - 1) {
            for col in sx.saturating_sub(small_r)..=(sx + small_r).min(n - 1) {
                u[row][col] = 0.5;
                v[row][col] = 0.25;
            }
        }
    }

    let mut u_next = vec![vec![0.0_f64; n]; n];
    let mut v_next = vec![vec![0.0_f64; n]; n];

    for _ in 0..iterations {
        for y in 0..n {
            for x in 0..n {
                // ラプラシアン (周期境界)
                let yp = if y == 0 { n - 1 } else { y - 1 };
                let yn = if y == n - 1 { 0 } else { y + 1 };
                let xp = if x == 0 { n - 1 } else { x - 1 };
                let xn = if x == n - 1 { 0 } else { x + 1 };

                let lap_u = 4.0f64.mul_add(-u[y][x], u[yp][x] + u[yn][x] + u[y][xp] + u[y][xn]);
                let lap_v = 4.0f64.mul_add(-v[y][x], v[yp][x] + v[yn][x] + v[y][xp] + v[y][xn]);

                let uv2 = u[y][x] * v[y][x] * v[y][x];
                u_next[y][x] = dt.mul_add(
                    feed.mul_add(1.0 - u[y][x], du.mul_add(lap_u, -uv2)),
                    u[y][x],
                );
                v_next[y][x] = dt.mul_add(
                    (feed + kill).mul_add(-v[y][x], dv.mul_add(lap_v, uv2)),
                    v[y][x],
                );
            }
        }
        std::mem::swap(&mut u, &mut u_next);
        std::mem::swap(&mut v, &mut v_next);
    }

    // V がしきい値以上のセルをドットとして出力
    let cell_w = bounds.w / usize_f64(n);
    let cell_h = bounds.h / usize_f64(n);
    let mut dots = Vec::new();

    #[allow(clippy::needless_range_loop)]
    for y in 0..n {
        for x in 0..n {
            if v[y][x] >= threshold {
                let px = cell_center(x, cell_w, bounds.x);
                let py = cell_center(y, cell_h, bounds.y);
                dots.push(LaserElement::Dot(px, py));
            }
        }
    }

    dots
}

// ──────────────────────────────────────────────────────
//  SVG出力
// ──────────────────────────────────────────────────────

/// `LaserElement群をSVG文字列に変換`
///
/// `elements`: パターン要素
/// `stroke_color`: 線/ドットの色(SVG fill/stroke)
/// `stroke_width`: 線幅 (mm)
/// `bounds`: `SVGのviewBox用`
#[must_use]
pub fn elements_to_svg(
    elements: &[LaserElement],
    stroke_color: &str,
    stroke_width: f64,
    bounds: &Bounds,
) -> String {
    let mut svg = String::with_capacity(elements.len() * 80);
    let _ = write!(
        svg,
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <svg xmlns=\"http://www.w3.org/2000/svg\"\n\
         \x20    viewBox=\"{} {} {} {}\"\n\
         \x20    width=\"{}mm\" height=\"{}mm\">\n",
        bounds.x, bounds.y, bounds.w, bounds.h, bounds.w, bounds.h
    );

    for elem in elements {
        match elem {
            LaserElement::Line(x1, y1, x2, y2) => {
                let _ = writeln!(
                    svg,
                    "<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" \
                     stroke=\"{stroke_color}\" stroke-width=\"{stroke_width}\"/>"
                );
            }
            LaserElement::Circle(cx, cy, r) => {
                let _ = writeln!(
                    svg,
                    "<circle cx=\"{cx:.3}\" cy=\"{cy:.3}\" r=\"{r:.3}\" \
                     fill=\"{stroke_color}\"/>"
                );
            }
            LaserElement::Dot(x, y) => {
                let half = stroke_width * 0.5;
                let _ = writeln!(
                    svg,
                    "<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{stroke_width:.3}\" \
                     height=\"{stroke_width:.3}\" fill=\"{stroke_color}\"/>",
                    x - half,
                    y - half
                );
            }
            LaserElement::Polyline(points) => {
                if points.is_empty() {
                    continue;
                }
                svg.push_str("<polyline points=\"");
                for (i, (x, y)) in points.iter().enumerate() {
                    if i > 0 {
                        svg.push(' ');
                    }
                    let _ = write!(svg, "{x:.3},{y:.3}");
                }
                let _ = writeln!(
                    svg,
                    "\" fill=\"none\" stroke=\"{stroke_color}\" \
                     stroke-width=\"{stroke_width}\"/>"
                );
            }
        }
    }

    svg.push_str("</svg>\n");
    svg
}

// ──────────────────────────────────────────────────────
//  ユーティリティ
// ──────────────────────────────────────────────────────

/// 範囲 `extent` を `cell` 幅で割った cell 数 (切上げ、負 / NaN → 0)
///
/// `f64 → usize` の単一 audit 点: `ceil().max(0.0)` 後なので符号なし、mm 単位の
/// 板サイズ / cell 幅で 2^53 を超えることはない
/// (`max(0.0)` の等しいゼロの符号は platform で割れうるが、直後の `as usize` が
/// 符号を消すので歯に関わらない)
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn cell_count(extent: f64, cell: f64) -> usize {
    raw_max_f64(
        (extent / cell).ceil(),
        0.0,
        crate::raw_minmax::Reason::IntCast,
    ) as usize
}

/// cell index → cell 中心の座標 (`origin + (i + 0.5) * cell`)
fn cell_center(i: usize, cell: f64, origin: f64) -> f64 {
    (usize_f64(i) + 0.5).mul_add(cell, origin)
}

/// `usize → f64` の単一 audit 点 (grid index / cell 数は 2^53 未満)
#[allow(clippy::cast_precision_loss)]
const fn usize_f64(i: usize) -> f64 {
    i as f64
}

/// 浮動小数の近似GCD(スピログラフの完全周期計算用)
///
/// 剰余が 0 になった時点の除数を返す 旧実装は `small < eps` で break する前に
/// 除数の繰り上げを通らず、最後の商を落としていた (`gcd(10,5)` が 10、
/// `gcd(10,7)` が 3) ハイポトロコイドの周期 `2π·r/gcd(R,r)` が短くなり、
/// 曲線が閉じないまま途中で切れる
#[allow(clippy::while_float)] // Euclid 互除法の float 版、終了条件は eps
fn gcd_f64(lhs: f64, rhs: f64) -> f64 {
    let mut big = lhs.abs();
    let mut small = rhs.abs();
    let eps = 1e-9;
    while small > eps {
        let remainder = big % small;
        big = small;
        small = remainder;
    }
    big
}

// ──────────────────────────────────────────────────────
//  テスト
// ──────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn card_bounds() -> Bounds {
        Bounds::new(0.0, 0.0, 86.0, 54.0)
    }

    // --- hatch ---

    #[test]
    fn test_hatch_horizontal() {
        let elems = hatch(0.0, 2.0, &card_bounds());
        assert!(!elems.is_empty());
        // 水平線は y 座標が一定
        for elem in &elems {
            if let LaserElement::Line(_, y1, _, y2) = elem {
                assert!((y1 - y2).abs() < 1e-9, "水平線のy座標が不一致");
            }
        }
    }

    #[test]
    fn test_hatch_vertical() {
        let elems = hatch(90.0, 2.0, &card_bounds());
        assert!(!elems.is_empty());
        for elem in &elems {
            if let LaserElement::Line(x1, _, x2, _) = elem {
                assert!((x1 - x2).abs() < 1e-9, "垂直線のx座標が不一致");
            }
        }
    }

    #[test]
    fn test_hatch_diagonal() {
        let elems = hatch(45.0, 3.0, &card_bounds());
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_hatch_zero_spacing() {
        let elems = hatch(0.0, 0.0, &card_bounds());
        assert!(elems.is_empty());
    }

    #[test]
    fn test_hatch_line_count() {
        let spacing = 2.0;
        let elems = hatch(0.0, spacing, &card_bounds());
        let expected = cell_count(54.0, spacing);
        // 端数による±1の誤差を許容
        assert!(
            elems.len().abs_diff(expected) <= 1,
            "線数 {} が期待値 {} と大幅に異なる",
            elems.len(),
            expected
        );
    }

    // --- crosshatch ---

    #[test]
    fn test_crosshatch() {
        let elems = crosshatch(3.0, &card_bounds());
        assert!(!elems.is_empty());
        let h_count = hatch(0.0, 3.0, &card_bounds()).len();
        let v_count = hatch(90.0, 3.0, &card_bounds()).len();
        assert_eq!(elems.len(), h_count + v_count);
    }

    // --- density_hatch ---

    #[test]
    fn test_density_hatch_uniform() {
        // 密度一定 → 等間隔ハッチと同等
        let elems = density_hatch(2.0, 2.0, 0.0, &card_bounds(), &|_, _| 0.5);
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_density_hatch_center_dense() {
        let bounds = card_bounds();
        let (cx, cy) = bounds.center();
        let max_dist = cx.hypot(cy);
        let elems = density_hatch(0.5, 4.0, 0.0, &bounds, &|x, y| {
            let dx = x - cx;
            let dy = y - cy;
            1.0 - dx.hypot(dy) / max_dist
        });
        assert!(!elems.is_empty());
    }

    // --- halftone ---

    #[test]
    fn test_halftone_uniform_black() {
        let elems = halftone(20.0, 0.5, &card_bounds(), &|_, _| 0.0);
        // 全黒 → 全セルが最大半径
        assert!(!elems.is_empty());
        for elem in &elems {
            if let LaserElement::Circle(_, _, r) = elem {
                assert!((*r - 0.5).abs() < 0.01);
            }
        }
    }

    #[test]
    fn test_halftone_uniform_white() {
        let elems = halftone(20.0, 0.5, &card_bounds(), &|_, _| 1.0);
        // 全白 → ドットなし
        assert!(elems.is_empty());
    }

    #[test]
    fn test_halftone_gradient() {
        let bounds = card_bounds();
        let elems = halftone(30.0, 0.4, &bounds, &|x, _| x / bounds.w);
        assert!(!elems.is_empty());
    }

    // --- dither ---

    #[test]
    fn test_dither_floyd_steinberg() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::FloydSteinberg, 50.0, &bounds, &|x, _| {
            x / 10.0
        });
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_dither_atkinson() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::Atkinson, 50.0, &bounds, &|_, y| y / 10.0);
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_dither_stucki() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::Stucki, 50.0, &bounds, &|x, y| {
            (x + y) / 20.0
        });
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_dither_jarvis() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::Jarvis, 50.0, &bounds, &|_, _| 0.3);
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_dither_bayer() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::Bayer4x4, 50.0, &bounds, &|x, _| x / 10.0);
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_dither_all_white() {
        let bounds = Bounds::new(0.0, 0.0, 5.0, 5.0);
        let elems = dither(DitherAlgorithm::FloydSteinberg, 50.0, &bounds, &|_, _| 1.0);
        assert!(elems.is_empty());
    }

    // --- guilloche ---

    #[test]
    fn test_guilloche_basic() {
        let elems = guilloche(10.0, 7.0, 5.0, 1000, &card_bounds());
        assert_eq!(elems.len(), 1);
        if let LaserElement::Polyline(pts) = &elems[0] {
            assert!(pts.len() > 100);
        }
    }

    #[test]
    fn test_guilloche_equal_radii() {
        // R == r → 単なる円
        let elems = guilloche(5.0, 5.0, 3.0, 500, &card_bounds());
        assert_eq!(elems.len(), 1);
    }

    // --- lissajous ---

    #[test]
    fn test_lissajous_basic() {
        let elems = lissajous(3.0, 2.0, PI * 0.5, 20.0, 1000, &card_bounds());
        assert_eq!(elems.len(), 1);
        if let LaserElement::Polyline(pts) = &elems[0] {
            assert_eq!(pts.len(), 1001);
        }
    }

    // --- rose ---

    #[test]
    fn test_rose_3_petals() {
        let elems = rose(3.0, 20.0, 500, &card_bounds());
        assert_eq!(elems.len(), 1);
    }

    #[test]
    fn test_rose_4_petals() {
        let elems = rose(2.0, 20.0, 500, &card_bounds());
        assert_eq!(elems.len(), 1);
    }

    // --- phyllotaxis ---

    #[test]
    fn test_phyllotaxis_basic() {
        let elems = phyllotaxis(500, 0.5, &card_bounds());
        assert!(!elems.is_empty());
        assert!(elems.len() <= 500);
    }

    #[test]
    fn test_phyllotaxis_clipping() {
        // 小さいバウンズ → 多くのドットがクリップされる
        let small = Bounds::new(40.0, 24.0, 6.0, 6.0);
        let elems = phyllotaxis(1000, 0.5, &small);
        assert!(elems.len() < 1000);
    }

    // --- turing ---

    #[test]
    fn test_turing_spots() {
        let bounds = Bounds::new(0.0, 0.0, 20.0, 20.0);
        let elems = turing(0.055, 0.062, 64, 5000, &bounds, 0.15);
        assert!(!elems.is_empty());
    }

    #[test]
    fn test_turing_low_resolution() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = turing(0.040, 0.060, 3, 100, &bounds, 0.2);
        // 解像度 < 4 → 空
        assert!(elems.is_empty());
    }

    // --- SVG出力 ---

    #[test]
    fn test_elements_to_svg() {
        let bounds = card_bounds();
        let elems = hatch(0.0, 5.0, &bounds);
        let svg = elements_to_svg(&elems, "#FFFFFF", 0.1, &bounds);
        assert!(svg.contains("<svg"));
        assert!(svg.contains("</svg>"));
        assert!(svg.contains("<line"));
    }

    #[test]
    fn test_svg_contains_polyline() {
        let bounds = card_bounds();
        let elems = guilloche(10.0, 7.0, 5.0, 200, &bounds);
        let svg = elements_to_svg(&elems, "#C0C0C0", 0.05, &bounds);
        assert!(svg.contains("<polyline"));
    }

    #[test]
    fn test_svg_contains_circles() {
        let bounds = card_bounds();
        let elems = halftone(20.0, 0.3, &bounds, &|_, _| 0.5);
        let svg = elements_to_svg(&elems, "#FFFFFF", 0.1, &bounds);
        assert!(svg.contains("<circle"));
    }

    #[test]
    fn test_svg_contains_dots() {
        let bounds = Bounds::new(0.0, 0.0, 10.0, 10.0);
        let elems = dither(DitherAlgorithm::FloydSteinberg, 30.0, &bounds, &|_, _| 0.3);
        let svg = elements_to_svg(&elems, "#FFFFFF", 0.08, &bounds);
        assert!(svg.contains("<rect"));
    }
}