File size: 126,337 Bytes
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
e46f6f7
 
 
 
018f164
 
 
 
e46f6f7
018f164
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
e46f6f7
 
 
018f164
e46f6f7
018f164
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b2882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
78b2882
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
e46f6f7
 
 
 
 
 
 
 
 
78b2882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
 
 
 
 
 
 
 
 
 
 
e46f6f7
c8a6842
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b2882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b2882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b2882
 
 
 
 
 
 
 
c8a6842
 
78b2882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a6842
 
78b2882
 
 
 
e46f6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
018f164
e46f6f7
c8a6842
 
e46f6f7
c8a6842
 
 
 
e46f6f7
78b2882
 
 
 
 
 
 
 
 
018f164
 
 
e46f6f7
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
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
'use strict';
// Pixel art engine behind the agentweb MCP pixel_* tools. A canvas is a
// palette-indexed grid saved as <session>/pixel/<name>.json (plus a native
// PNG next to it). Every pixel is either fully transparent or exactly one
// palette colour, and every operation is deterministic (seeded), so the
// output is real pixel art: no anti-aliasing, no half-transparent edges, no
// stray colours. The idea is Texel Studio's: the model paints with tools
// instead of a diffusion model guessing pixels.
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');

const DIR = 'pixel';
const MAX_SIDE = 512;
const MAX_COLORS = 255;
const MAX_OPS = 400;
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
const ASCII_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

const PALETTES = {
  endesga32: {
    note: 'Endesga 32: warm, versatile, good default for games (terrain, characters, buildings).',
    colors: 'be4a2f d77643 ead4aa e4a672 b86f50 733e39 3e2731 a22633 e43b44 f77622 feae34 fee761 63c74d 3e8948 265c42 193c3e 124e89 0099db 2ce8f5 ffffff c0cbdc 8b9bb4 5a6988 3a4466 262b44 181425 ff0044 68386c b55088 f6757a e8b796 c28569',
  },
  pico8: {
    note: 'PICO-8: 16 bright colours, retro console look.',
    colors: '000000 1d2b53 7e2553 008751 ab5236 5f574f c2c3c7 fff1e8 ff004d ffa300 ffec27 00e436 29adff 83769c ff77a8 ffccaa',
  },
  sweetie16: {
    note: 'Sweetie 16: soft, harmonious 16 colours.',
    colors: '1a1c2c 5d275d b13e53 ef7d57 ffcd75 a7f070 38b764 257179 29366f 3b5dc9 41a6f6 73eff7 f4f4f4 94b0c2 566c86 333c57',
  },
  db16: {
    note: 'DawnBringer 16: classic, natural tones.',
    colors: '140c1c 442434 30346d 4e4a4e 854c30 346524 d04648 757161 597dce d27d2c 8595a1 6daa2c d2aa99 6dc2ca dad45e deeed6',
  },
  gameboy: {
    note: 'Game Boy: 4 greens.',
    colors: '0f380f 306230 8bac0f 9bbc0f',
  },
};

class PixelError extends Error {}

// ---- colours ----

function parseHex(value) {
  if (typeof value !== 'string') return null;
  let s = value.trim().replace(/^#/, '');
  if (/^[0-9a-f]{3}$/i.test(s)) s = s.replace(/./g, (c) => c + c);
  // #rrggbbaa: a translucent palette colour (ground shadows, glass, water).
  if (/^[0-9a-f]{8}$/i.test(s)) {
    const a = parseInt(s.slice(6, 8), 16);
    const rgb = [parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16)];
    return a === 255 ? rgb : [...rgb, a];
  }
  if (!/^[0-9a-f]{6}$/i.test(s)) return null;
  return [parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16)];
}

function isTranslucent(rgb) {
  return rgb.length > 3 && rgb[3] < 255;
}

function toHex(rgb) {
  const parts = isTranslucent(rgb) ? rgb.slice(0, 4) : rgb.slice(0, 3);
  return `#${parts.map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')}`;
}

function dist2(a, b) {
  // Weighted RGB distance (closer to perceived difference than plain RGB).
  const dr = a[0] - b[0];
  const dg = a[1] - b[1];
  const db = a[2] - b[2];
  const rm = (a[0] + b[0]) / 2;
  return (2 + rm / 256) * dr * dr + 4 * dg * dg + (2 + (255 - rm) / 256) * db * db;
}

function luminance(rgb) {
  return 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
}

// Palette argument: a preset name, a list of hex colours, or a string of them.
function resolvePalette(value, fallback = 'endesga32') {
  let list = value === undefined || value === null || value === '' ? fallback : value;
  if (typeof list === 'string' && /^lospec:/i.test(list.trim())) {
    const key = list.trim().slice(7).trim().toLowerCase();
    const found = lospecPalettes()[key];
    if (!found) {
      const near = findPalettes(key, 8).map((p) => `lospec:${p.key}`);
      throw new PixelError(`Lospec paleti bulunamadı: ${key}.${near.length ? ` Yakın olanlar: ${near.join(', ')}` : ''} (pixel_rules palettes ile ara)`);
    }
    list = found.colors;
  } else if (typeof list === 'string') {
    const preset = PALETTES[list.trim().toLowerCase()];
    list = preset ? preset.colors.split(/\s+/) : list.split(/[\s,]+/).filter(Boolean);
  }
  if (!Array.isArray(list) || !list.length) throw new PixelError('palette boş.');
  const out = [];
  for (const item of list) {
    const rgb = parseHex(String(item));
    if (!rgb) throw new PixelError(`Geçersiz renk: ${item} (#rrggbb bekleniyor; hazır paletler: ${Object.keys(PALETTES).join(', ')})`);
    const hex = toHex(rgb);
    if (!out.includes(hex)) out.push(hex);
  }
  if (out.length > MAX_COLORS) throw new PixelError(`Palette en fazla ${MAX_COLORS} renk olabilir.`);
  return out;
}

// 2006 Lospec palettes (with-pebbly/aseprite-ai-artist, MIT): vendor/pebbly/palettes.json,
// { key: { name, author, colors: [#hex] } }. Loaded on first use.
const VENDOR = path.join(__dirname, '..', 'vendor');
let lospecCache = null;

function lospecPalettes() {
  if (!lospecCache) {
    try {
      lospecCache = JSON.parse(fs.readFileSync(path.join(VENDOR, 'pebbly', 'palettes.json'), 'utf8'));
    } catch {
      lospecCache = {};
    }
  }
  return lospecCache;
}

// Search by key/name words; optional colour count range. Exact key first, then name matches.
function findPalettes(query, limit = 20, { min = 0, max = 256 } = {}) {
  const words = String(query || '').toLowerCase().split(/[\s_-]+/).filter(Boolean);
  const out = [];
  for (const [key, p] of Object.entries(lospecPalettes())) {
    const n = p.colors.length;
    if (n < min || n > max) continue;
    const hay = `${key} ${String(p.name || '').toLowerCase()}`;
    if (words.length && !words.every((w) => hay.includes(w))) continue;
    out.push({ key, name: p.name, author: p.author, colors: p.colors, score: key === words.join('-') ? 0 : key.startsWith(words[0] || '') ? 1 : 2 });
  }
  return out.sort((a, b) => a.score - b.score).slice(0, limit);
}

// ---- canvas ----

class Canvas {
  constructor(w, h, palette, data) {
    this.w = w;
    this.h = h;
    this.palette = palette.slice();
    this.rgb = this.palette.map(parseHex);
    this.data = data || new Uint8Array(w * h);
  }

  get(x, y) {
    return x >= 0 && y >= 0 && x < this.w && y < this.h ? this.data[y * this.w + x] : 0;
  }

  set(x, y, v) {
    if (x >= 0 && y >= 0 && x < this.w && y < this.h) this.data[y * this.w + x] = v;
  }

  // Palette slot (1-based; 0 is transparent) for a hex colour, adding it when allowed.
  slotFor(hex, add) {
    const i = this.palette.indexOf(hex);
    if (i >= 0) return i + 1;
    if (!add) return -1;
    if (this.palette.length >= MAX_COLORS) throw new PixelError(`Palet dolu (${MAX_COLORS} renk).`);
    this.palette.push(hex);
    this.rgb.push(parseHex(hex));
    return this.palette.length;
  }

  // Nearest palette colour; translucent entries only match translucent queries.
  nearest(rgb) {
    let best = 0;
    let bestD = Infinity;
    const want = isTranslucent(rgb);
    for (let i = 0; i < this.rgb.length; i++) {
      if (isTranslucent(this.rgb[i]) !== want && this.rgb.some((c) => isTranslucent(c) === want)) continue;
      const d = dist2(rgb, this.rgb[i]) + (want ? (rgb[3] - this.rgb[i][3]) ** 2 * 4 : 0);
      if (d < bestD) {
        bestD = d;
        best = i;
      }
    }
    return best + 1;
  }

  clone() {
    return new Canvas(this.w, this.h, this.palette, new Uint8Array(this.data));
  }

  usage() {
    const counts = new Map();
    for (const v of this.data) counts.set(v, (counts.get(v) || 0) + 1);
    return counts;
  }

  toJSON() {
    return { version: 1, w: this.w, h: this.h, palette: this.palette, data: Buffer.from(this.data).toString('base64') };
  }

  static fromJSON(obj) {
    if (!obj || !Number.isInteger(obj.w) || !Number.isInteger(obj.h) || !Array.isArray(obj.palette)) throw new PixelError('Bozuk tuval dosyası.');
    const data = new Uint8Array(Buffer.from(String(obj.data || ''), 'base64'));
    if (data.length !== obj.w * obj.h) throw new PixelError('Bozuk tuval dosyası (boyut uyuşmuyor).');
    return new Canvas(obj.w, obj.h, obj.palette, data);
  }
}

function checkName(name) {
  if (typeof name !== 'string' || !NAME_RE.test(name)) throw new PixelError('name harf/rakam/-/_ olmalı (en fazla 64 karakter), ör. "grass_tile".');
  return name;
}

function checkSize(w, h) {
  if (!Number.isInteger(w) || !Number.isInteger(h) || w < 1 || h < 1 || w > MAX_SIDE || h > MAX_SIDE) {
    throw new PixelError(`Boyut 1-${MAX_SIDE} arası tam sayı olmalı.`);
  }
}

function canvasPath(cwd, name) {
  return path.join(cwd, DIR, `${checkName(name)}.json`);
}

function load(cwd, name) {
  const file = canvasPath(cwd, name);
  let raw;
  try {
    raw = fs.readFileSync(file, 'utf8');
  } catch {
    const known = list(cwd).map((c) => c.name);
    throw new PixelError(`Tuval bulunamadı: ${name}${known.length ? ` (var olanlar: ${known.slice(0, 30).join(', ')})` : ' (önce pixel_new ile oluştur)'}`);
  }
  return Canvas.fromJSON(JSON.parse(raw));
}

// Saves the canvas and its native-size PNG; returns the PNG path.
function save(cwd, name, canvas) {
  const file = canvasPath(cwd, name);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, JSON.stringify(canvas.toJSON()));
  const png = path.join(path.dirname(file), `${name}.png`);
  fs.writeFileSync(png, encodePNG(canvas.w, canvas.h, render(canvas, { scale: 1 })));
  return png;
}

function list(cwd) {
  const dir = path.join(cwd, DIR);
  let names = [];
  try {
    names = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));
  } catch {
    return [];
  }
  const out = [];
  for (const f of names.sort()) {
    try {
      const obj = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
      out.push({ name: f.slice(0, -5), w: obj.w, h: obj.h, colors: obj.palette.length });
    } catch {
      // not a canvas
    }
  }
  return out;
}

// ---- PNG ----

const CRC_TABLE = (() => {
  const t = new Uint32Array(256);
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    t[n] = c >>> 0;
  }
  return t;
})();

function crc32(buf) {
  let c = 0xffffffff;
  for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
  return (c ^ 0xffffffff) >>> 0;
}

function pngChunk(type, data) {
  const len = Buffer.alloc(4);
  len.writeUInt32BE(data.length);
  const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
  const crc = Buffer.alloc(4);
  crc.writeUInt32BE(crc32(body));
  return Buffer.concat([len, body, crc]);
}

function encodePNG(w, h, rgba) {
  const stride = w * 4;
  const raw = Buffer.alloc((stride + 1) * h);
  for (let y = 0; y < h; y++) Buffer.from(rgba.buffer, rgba.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1);
  const ihdr = Buffer.alloc(13);
  ihdr.writeUInt32BE(w, 0);
  ihdr.writeUInt32BE(h, 4);
  ihdr[8] = 8; // bit depth
  ihdr[9] = 6; // RGBA
  return Buffer.concat([
    Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
    pngChunk('IHDR', ihdr),
    pngChunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
    pngChunk('IEND', Buffer.alloc(0)),
  ]);
}

// PNG or JPEG (agy's image generator writes JPEG even into .png files).
function decodeImage(buf) {
  if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) {
    const { PNG } = require('pngjs');
    const img = PNG.sync.read(buf);
    return { w: img.width, h: img.height, data: new Uint8Array(img.data) };
  }
  if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8) {
    const jpeg = require('jpeg-js');
    const img = jpeg.decode(buf, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024, maxResolutionInMP: 64 });
    return { w: img.width, h: img.height, data: img.data };
  }
  throw new PixelError('Yalnızca PNG ve JPEG görseller okunabiliyor.');
}

// Real image type of a file, whatever its extension says.
function imageType(buf) {
  if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) return 'png';
  if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8) return 'jpg';
  if (buf.length > 12 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') return 'webp';
  if (buf.length > 6 && buf.toString('ascii', 0, 3) === 'GIF') return 'gif';
  return null;
}

// Box-filtered preview of any decoded image (for showing Gemini's output to the model).
function thumbnail(img, maxSide) {
  const scale = Math.min(1, maxSide / Math.max(img.w, img.h));
  const w = Math.max(1, Math.round(img.w * scale));
  const h = Math.max(1, Math.round(img.h * scale));
  const out = new Uint8Array(w * h * 4);
  for (let y = 0; y < h; y++) {
    const y0 = Math.floor((y * img.h) / h);
    const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * img.h) / h));
    for (let x = 0; x < w; x++) {
      const x0 = Math.floor((x * img.w) / w);
      const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * img.w) / w));
      const acc = [0, 0, 0, 0];
      let n = 0;
      for (let sy = y0; sy < y1; sy++) {
        for (let sx = x0; sx < x1; sx++) {
          const i = (sy * img.w + sx) * 4;
          for (let k = 0; k < 4; k++) acc[k] += img.data[i + k];
          n++;
        }
      }
      for (let k = 0; k < 4; k++) out[(y * w + x) * 4 + k] = Math.round(acc[k] / n);
    }
  }
  return { w, h, data: out };
}

// ---- rendering ----

// RGBA buffer of the canvas, scaled by an integer (nearest neighbour).
// checker: grey checkerboard behind transparent pixels (previews only).
// grid: line every `grid` source pixels (previews only).
function render(canvas, { scale = 1, checker = false, grid = 0, region = null } = {}) {
  const rx = region ? region.x : 0;
  const ry = region ? region.y : 0;
  const cw = region ? region.w : canvas.w;
  const ch = region ? region.h : canvas.h;
  const W = cw * scale;
  const H = ch * scale;
  const out = new Uint8Array(W * H * 4);
  for (let y = 0; y < H; y++) {
    const sy = ry + Math.floor(y / scale);
    for (let x = 0; x < W; x++) {
      const sx = rx + Math.floor(x / scale);
      const v = canvas.get(sx, sy);
      const o = (y * W + x) * 4;
      if (v) {
        const c = canvas.rgb[v - 1];
        const a = c.length > 3 ? c[3] : 255;
        if (a < 255 && checker) {
          // Preview: blend over the checkerboard so the shadow is visible.
          const bg = (Math.floor(x / Math.max(4, scale)) + Math.floor(y / Math.max(4, scale))) % 2 === 0 ? 204 : 170;
          out[o] = Math.round((c[0] * a + bg * (255 - a)) / 255);
          out[o + 1] = Math.round((c[1] * a + bg * (255 - a)) / 255);
          out[o + 2] = Math.round((c[2] * a + bg * (255 - a)) / 255);
          out[o + 3] = 255;
        } else {
          out[o] = c[0];
          out[o + 1] = c[1];
          out[o + 2] = c[2];
          out[o + 3] = a;
        }
      } else if (checker) {
        const light = (Math.floor(x / Math.max(4, scale)) + Math.floor(y / Math.max(4, scale))) % 2 === 0;
        out[o] = out[o + 1] = out[o + 2] = light ? 204 : 170;
        out[o + 3] = 255;
      }
      if (grid && scale >= 4) {
        const onLine = (x % scale === 0 && (Math.floor(x / scale) + rx) % grid === 0) || (y % scale === 0 && (Math.floor(y / scale) + ry) % grid === 0);
        if (onLine) {
          out[o] = 255;
          out[o + 1] = 0;
          out[o + 2] = 255;
          out[o + 3] = 255;
        }
      }
    }
  }
  return out;
}

function autoScale(w, h, target = 384) {
  return Math.max(1, Math.min(32, Math.floor(target / Math.max(w, h))));
}

function previewImage(canvas, opts = {}) {
  const region = opts.region || null;
  const w = region ? region.w : canvas.w;
  const h = region ? region.h : canvas.h;
  const scale = opts.scale || autoScale(w, h, opts.target || 384);
  const png = encodePNG(w * scale, h * scale, render(canvas, { scale, checker: true, grid: opts.grid || 0, region }));
  return { type: 'image', data: png.toString('base64'), mimeType: 'image/png' };
}

function asciiView(canvas, region) {
  const r = region || { x: 0, y: 0, w: canvas.w, h: canvas.h };
  const used = new Set();
  const rows = [];
  const pad = String(r.y + r.h - 1).length;
  for (let y = r.y; y < r.y + r.h; y++) {
    let line = '';
    for (let x = r.x; x < r.x + r.w; x++) {
      const v = canvas.get(x, y);
      if (v) used.add(v);
      line += v ? ASCII_CHARS[v - 1] || '?' : '.';
    }
    rows.push(`${String(y).padStart(pad)} ${line}`);
  }
  const legend = [...used].sort((a, b) => a - b).map((v) => `${ASCII_CHARS[v - 1] || '?'}=${canvas.palette[v - 1]}`);
  return `x=${r.x}..${r.x + r.w - 1}, y=${r.y}..${r.y + r.h - 1}; "." saydam\n${rows.join('\n')}\nRenkler: ${legend.join(' ') || '(boş)'}`;
}

// Share of each colour among the opaque pixels, darkest first (for self-review).
function toneStats(canvas, region) {
  const r = region || { x: 0, y: 0, w: canvas.w, h: canvas.h };
  const counts = new Map();
  let total = 0;
  for (let y = r.y; y < r.y + r.h; y++) {
    for (let x = r.x; x < r.x + r.w; x++) {
      const v = canvas.get(x, y);
      if (!v || isTranslucent(canvas.rgb[v - 1])) continue;
      counts.set(v, (counts.get(v) || 0) + 1);
      total++;
    }
  }
  const rows = [...counts].sort((a, b) => luminance(canvas.rgb[a[0] - 1]) - luminance(canvas.rgb[b[0] - 1]));
  return `Ton dağılımı (koyudan açığa, ${total} opak piksel, ${rows.length} renk): ${rows.map(([v, n]) => `${canvas.palette[v - 1]} %${Math.round((100 * n) / Math.max(1, total))}`).join(', ')}`;
}

// ---- drawing ----

function mulberry32(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function int(value, name, def) {
  if (value === undefined || value === null) {
    if (def === undefined) throw new PixelError(`${name} gerekli.`);
    return def;
  }
  const n = Number(value);
  if (!Number.isFinite(n)) throw new PixelError(`${name} sayı olmalı.`);
  return Math.round(n);
}

// Hand-drawn leaf sprites for the foliage op, grouped by the way they point.
// 0 = deep gap, 1 = dark rim, 2 = mid, 3 = light, 4 = highlight.
const LEAF_SETS = {
  right: [
    ['.33...', '14332.', '.12222', '..111.'],
    ['.3....', '1432..', '.1322.', '..1221', '...11.'],
  ],
  left: [
    ['...33.', '.23341', '22221.', '.111..'],
    ['....3.', '..2341', '.2231.', '1221..', '.11...'],
  ],
  down: [
    ['.33.', '1432', '1322', '.221', '.11.'],
    ['.3..', '143.', '1322', '.122', '..11'],
  ],
  up: [
    ['..3.', '.343', '1332', '1221', '.11.'],
    ['...3', '.234', '1231', '121.', '.1..'],
  ],
  center: [
    ['.34.', '1332', '1222', '.11.'],
    ['33..', '1432', '.122', '..1.'],
  ],
};

const BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];

class Painter {
  constructor(canvas, { cwd = null, symmetry = null } = {}) {
    this.c = canvas;
    this.cwd = cwd;
    this.symmetry = symmetry;
    this.warnings = new Set();
    this.only = null;
  }

  // Colour argument → palette slot: hex (snapped to the nearest palette
  // colour when it is not in the palette), 0-based palette index, or
  // null/"transparent" to erase.
  color(value, name = 'color') {
    if (value === null || value === undefined) {
      if (name === 'color') throw new PixelError('color gerekli (#rrggbb, palet sırası ya da "transparent").');
      return 0;
    }
    if (typeof value === 'number') {
      if (!Number.isInteger(value) || value < 0 || value >= this.c.palette.length) throw new PixelError(`${name}: palet sırası 0-${this.c.palette.length - 1} olmalı.`);
      return value + 1;
    }
    const s = String(value).trim().toLowerCase();
    if (s === 'transparent' || s === 'none' || s === 'clear') return 0;
    const rgb = parseHex(s);
    if (!rgb) throw new PixelError(`${name}: geçersiz renk "${value}".`);
    const hex = toHex(rgb);
    const exact = this.c.palette.indexOf(hex);
    if (exact >= 0) return exact + 1;
    const near = this.c.nearest(rgb);
    this.warnings.add(`${hex} palette yok → ${this.c.palette[near - 1]} kullanıldı`);
    return near;
  }

  allowed(x, y) {
    if (!this.only) return true;
    const v = this.c.get(x, y);
    if (this.only === 'opaque') return v !== 0;
    if (this.only === 'transparent') return v === 0;
    return v === this.only;
  }

  paint(x, y, v) {
    const points = [[x, y]];
    const s = this.symmetry;
    if (s === 'x' || s === 'both') points.push([this.c.w - 1 - x, y]);
    if (s === 'y' || s === 'both') points.push([x, this.c.h - 1 - y]);
    if (s === 'both') points.push([this.c.w - 1 - x, this.c.h - 1 - y]);
    for (const [px, py] of points) {
      if (this.allowed(px, py)) this.c.set(px, py, v);
    }
  }

  rectArgs(op) {
    const x = int(op.x, 'x', 0);
    const y = int(op.y, 'y', 0);
    return { x, y, w: int(op.w, 'w', this.c.w - x), h: int(op.h, 'h', this.c.h - y) };
  }

  line(x0, y0, x1, y1, v) {
    const dx = Math.abs(x1 - x0);
    const dy = -Math.abs(y1 - y0);
    const sx = x0 < x1 ? 1 : -1;
    const sy = y0 < y1 ? 1 : -1;
    let err = dx + dy;
    for (let guard = 0; guard < 4 * MAX_SIDE; guard++) {
      this.paint(x0, y0, v);
      if (x0 === x1 && y0 === y1) break;
      const e2 = 2 * err;
      if (e2 >= dy) {
        err += dy;
        x0 += sx;
      }
      if (e2 <= dx) {
        err += dx;
        y0 += sy;
      }
    }
  }

  // Paints a shape given as a membership test inside a bounding box:
  // filled, or only its 4-connected border (clean 1px outline, no doubled corners).
  shape(bx, by, bw, bh, inside, v, fill) {
    for (let y = by; y < by + bh; y++) {
      for (let x = bx; x < bx + bw; x++) {
        if (!inside(x, y)) continue;
        if (!fill && inside(x - 1, y) && inside(x + 1, y) && inside(x, y - 1) && inside(x, y + 1)) continue;
        this.paint(x, y, v);
      }
    }
  }

  // Default leaves style: pointed 4x3 leaves on a jittered grid. The
  // silhouette becomes the dark tone, every leaf gets a lit tip, a body in its
  // shade and a darkest-tone shadow under it; leaves are painted bottom-up so
  // upper leaves cast their shadow over the ones below (crisp, Stardew-like).
  leafStyle({ ramp, mask, free, shadeAt, rand, density, op, clusters }) {
    const n = ramp.length;
    const deep = ramp[0];
    const base = ramp[1];
    for (let y = 0; y < this.c.h; y++) for (let x = 0; x < this.c.w; x++) if (mask(x, y)) this.paint(x, y, base);
    // roles: 2 = tip (t+1), 1 = body (t), 0 = shadow (darkest)
    const LEAVES = [
      [[0, 0, 2], [1, 0, 1], [2, 0, 1], [1, 1, 1], [2, 1, 1], [3, 1, 1], [0, 1, 0], [1, 2, 0], [2, 2, 0], [3, 2, 0]],
      [[3, 0, 2], [2, 0, 1], [1, 0, 1], [2, 1, 1], [1, 1, 1], [0, 1, 1], [3, 1, 0], [2, 2, 0], [1, 2, 0], [0, 2, 0]],
      [[0, 0, 2], [1, 0, 1], [1, 1, 1], [2, 1, 1], [2, 2, 1], [0, 1, 0], [1, 2, 0], [2, 3, 0], [3, 2, 0]],
      [[2, 0, 2], [1, 0, 1], [1, 1, 1], [0, 1, 1], [0, 2, 1], [2, 1, 0], [1, 2, 0], [0, 3, 0]],
      [[0, 0, 2], [1, 0, 1], [1, 1, 1], [0, 1, 0], [1, 2, 0], [2, 1, 0]],
      [[1, 0, 2], [0, 1, 1], [1, 1, 1], [2, 1, 1], [0, 2, 0], [1, 2, 0], [2, 2, 0]],
    ];
    const step = Math.max(2, Math.round(3.2 / Math.sqrt(density)));
    const spots = [];
    for (let gy = -2; gy < this.c.h; gy += step) {
      const shift = Math.floor(rand() * step);
      for (let gx = -2 - shift; gx < this.c.w; gx += step) {
        const x = gx + Math.floor(rand() * step);
        const y = gy + Math.floor(rand() * step);
        if (!mask(x + 1, y + 1)) continue;
        // Leaves point away from the centre of their clump (radial, like real foliage).
        let best = clusters[0];
        let bestD = Infinity;
        for (const c of clusters) {
          const d = Math.hypot(x - c.cx, y - c.cy) / c.r;
          if (d < bestD) {
            bestD = d;
            best = c;
          }
        }
        const ang = Math.atan2(y - best.cy, x - best.cx) + (rand() - 0.5) * 1.2;
        const dirs = ang > -Math.PI / 4 && ang <= Math.PI / 4 ? [0, 2] : ang > Math.PI / 4 && ang <= (3 * Math.PI) / 4 ? [2, 3, 4] : ang > -(3 * Math.PI) / 4 && ang <= -Math.PI / 4 ? [5, 4] : [1, 3];
        const leaf = LEAVES[dirs[Math.floor(rand() * dirs.length)]];
        spots.push({ x, y, tone: Math.max(1, shadeAt(x + 1, y + 1)), leaf: rand() < 0.15 ? LEAVES[Math.floor(rand() * LEAVES.length)] : leaf });
      }
    }
    spots.sort((a, b) => b.y - a.y || a.x - b.x);
    const flower = op.accent === undefined || op.accent === null ? null : this.color(op.accent, 'accent');
    const accentRate = Math.max(0, Math.min(0.5, Number(op.accent_rate) || 0.04));
    const touches = (x, y) => mask(x - 1, y) || mask(x + 1, y) || mask(x, y - 1) || mask(x, y + 1);
    for (const s of spots) {
      for (const [dx, dy, role] of s.leaf) {
        const x = s.x + dx;
        const y = s.y + dy;
        const v = role === 0 ? deep : ramp[Math.min(n - 1, s.tone + (role === 2 ? 1 : 0))];
        // Lit leaves may poke out past the silhouette: a leafy, ragged edge.
        if (mask(x, y) || (role !== 0 && s.tone <= 2 && free(x, y) && touches(x, y))) this.paint(x, y, v);
      }
      if (flower && rand() < accentRate) this.paint(s.x + 1, s.y + 1, flower);
    }
  }

  apply(op) {
    if (!op || typeof op !== 'object') throw new PixelError('Her işlem bir nesne olmalı: {"op": "rect", ...}');
    const kind = String(op.op || '').toLowerCase();
    this.only = op.only === undefined || op.only === null ? null : op.only === 'opaque' || op.only === 'transparent' ? op.only : this.color(op.only, 'only') || 'transparent';
    const fill = op.fill !== false;
    switch (kind) {
      case 'pixel':
        this.paint(int(op.x, 'x'), int(op.y, 'y'), this.color(op.color));
        return;
      case 'pixels': {
        if (!Array.isArray(op.points)) throw new PixelError('pixels: points [[x,y], ...] ya da [[x,y,renk], ...] olmalı.');
        const base = op.color === undefined ? null : this.color(op.color);
        for (const p of op.points) {
          if (!Array.isArray(p) || p.length < 2) throw new PixelError('pixels: her nokta [x,y] ya da [x,y,renk] olmalı.');
          const v = p.length > 2 ? this.color(p[2]) : base;
          if (v === null) throw new PixelError('pixels: renk yok (color ya da [x,y,renk]).');
          this.paint(int(p[0], 'x'), int(p[1], 'y'), v);
        }
        return;
      }
      case 'rect': {
        const r = this.rectArgs(op);
        const v = this.color(op.color);
        this.shape(r.x, r.y, r.w, r.h, (x, y) => x >= r.x && y >= r.y && x < r.x + r.w && y < r.y + r.h, v, fill);
        return;
      }
      case 'line':
        this.line(int(op.x1, 'x1'), int(op.y1, 'y1'), int(op.x2, 'x2'), int(op.y2, 'y2'), this.color(op.color));
        return;
      case 'circle':
      case 'ellipse': {
        let x;
        let y;
        let w;
        let h;
        if (kind === 'circle') {
          const r = int(op.r, 'r');
          x = int(op.cx, 'cx') - r;
          y = int(op.cy, 'cy') - r;
          w = h = 2 * r + 1;
        } else {
          ({ x, y, w, h } = this.rectArgs(op));
        }
        const cx = x + w / 2;
        const cy = y + h / 2;
        const rx = w / 2;
        const ry = h / 2;
        const inside = (px, py) => {
          const dx = (px + 0.5 - cx) / rx;
          const dy = (py + 0.5 - cy) / ry;
          return dx * dx + dy * dy <= 1.0001;
        };
        this.shape(x, y, w, h, inside, this.color(op.color), fill);
        return;
      }
      case 'polygon': {
        const pts = Array.isArray(op.points) ? op.points.map((p) => [int(p && p[0], 'x'), int(p && p[1], 'y')]) : null;
        if (!pts || pts.length < 3) throw new PixelError('polygon: en az 3 köşe [[x,y], ...] gerekli.');
        const v = this.color(op.color);
        if (fill) {
          const ys = pts.map((p) => p[1]);
          for (let y = Math.min(...ys); y <= Math.max(...ys); y++) {
            const xs = [];
            for (let i = 0; i < pts.length; i++) {
              const [ax, ay] = pts[i];
              const [bx, by] = pts[(i + 1) % pts.length];
              if (ay === by) continue;
              if ((y >= ay && y < by) || (y >= by && y < ay)) xs.push(ax + ((y - ay) * (bx - ax)) / (by - ay));
            }
            xs.sort((a, b) => a - b);
            for (let i = 0; i + 1 < xs.length; i += 2) {
              for (let x = Math.ceil(xs[i]); x <= Math.floor(xs[i + 1]); x++) this.paint(x, y, v);
            }
          }
        }
        for (let i = 0; i < pts.length; i++) {
          const [ax, ay] = pts[i];
          const [bx, by] = pts[(i + 1) % pts.length];
          this.line(ax, ay, bx, by, v);
        }
        return;
      }
      case 'fill': {
        const x0 = int(op.x, 'x');
        const y0 = int(op.y, 'y');
        const v = this.color(op.color);
        const target = this.c.get(x0, y0);
        if (target === v) return;
        if (op.contiguous === false) {
          for (let i = 0; i < this.c.data.length; i++) if (this.c.data[i] === target) this.c.data[i] = v;
          return;
        }
        const stack = [[x0, y0]];
        while (stack.length) {
          const [x, y] = stack.pop();
          if (x < 0 || y < 0 || x >= this.c.w || y >= this.c.h || this.c.get(x, y) !== target) continue;
          this.c.set(x, y, v);
          stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
        }
        return;
      }
      case 'grid': {
        if (!Array.isArray(op.rows) || !op.legend || typeof op.legend !== 'object') throw new PixelError('grid: rows ["..ab", ...] ve legend {"a": "#hex"} gerekli.');
        const x0 = int(op.x, 'x', 0);
        const y0 = int(op.y, 'y', 0);
        const legend = new Map();
        for (const [ch, col] of Object.entries(op.legend)) legend.set(ch, this.color(col, `legend "${ch}"`));
        op.rows.forEach((row, dy) => {
          [...String(row)].forEach((ch, dx) => {
            if (legend.has(ch)) this.paint(x0 + dx, y0 + dy, legend.get(ch));
            else if (ch !== '.' && ch !== ' ') throw new PixelError(`grid: "${ch}" legend'da yok (boş bırakmak için "." kullan).`);
          });
        });
        return;
      }
      case 'noise': {
        const r = this.rectArgs(op);
        const colors = (Array.isArray(op.colors) ? op.colors : [op.color]).map((c) => this.color(c));
        const weights = Array.isArray(op.weights) && op.weights.length === colors.length ? op.weights.map(Number) : colors.map(() => 1);
        const total = weights.reduce((a, b) => a + b, 0) || 1;
        const density = op.density === undefined ? 1 : Math.max(0, Math.min(1, Number(op.density)));
        const rand = mulberry32(int(op.seed, 'seed', 1));
        for (let y = r.y; y < r.y + r.h; y++) {
          for (let x = r.x; x < r.x + r.w; x++) {
            if (rand() >= density) continue;
            let pick = rand() * total;
            let i = 0;
            while (i < colors.length - 1 && pick >= weights[i]) pick -= weights[i++];
            this.paint(x, y, colors[i]);
          }
        }
        return;
      }
      case 'dither': {
        const r = this.rectArgs(op);
        const from = this.color(op.from, 'from');
        const to = this.color(op.to, 'to');
        const dir = String(op.direction || 'down');
        const pattern = String(op.pattern || 'bayer4');
        for (let y = r.y; y < r.y + r.h; y++) {
          for (let x = r.x; x < r.x + r.w; x++) {
            const fx = (x - r.x + 0.5) / r.w;
            const fy = (y - r.y + 0.5) / r.h;
            const t = dir === 'up' ? 1 - fy : dir === 'right' ? fx : dir === 'left' ? 1 - fx : fy;
            const thr = pattern === 'checker' ? ((x + y) % 2 ? 0.75 : 0.25) : (BAYER4[(y & 3) * 4 + (x & 3)] + 0.5) / 16;
            this.paint(x, y, t > thr ? to : from);
          }
        }
        return;
      }
      case 'voronoi': {
        const r = this.rectArgs(op);
        const n = Math.max(2, Math.min(256, int(op.cells, 'cells', 8)));
        const colors = (Array.isArray(op.colors) ? op.colors : [op.color]).map((c) => this.color(c));
        const edge = op.edge === undefined || op.edge === null ? null : this.color(op.edge, 'edge');
        const wrap = !!op.wrap;
        const rand = mulberry32(int(op.seed, 'seed', 1));
        const seeds = [];
        for (let i = 0; i < n; i++) seeds.push([rand() * r.w, rand() * r.h, colors[Math.floor(rand() * colors.length)]]);
        const owner = new Int32Array(r.w * r.h);
        for (let y = 0; y < r.h; y++) {
          for (let x = 0; x < r.w; x++) {
            let best = 0;
            let bestD = Infinity;
            for (let i = 0; i < n; i++) {
              let dx = Math.abs(x + 0.5 - seeds[i][0]);
              let dy = Math.abs(y + 0.5 - seeds[i][1]);
              if (wrap) {
                dx = Math.min(dx, r.w - dx);
                dy = Math.min(dy, r.h - dy);
              }
              const d = dx * dx + dy * dy;
              if (d < bestD) {
                bestD = d;
                best = i;
              }
            }
            owner[y * r.w + x] = best;
          }
        }
        const at = (x, y) => {
          if (wrap) return owner[((y + r.h) % r.h) * r.w + ((x + r.w) % r.w)];
          return x < r.w && y < r.h ? owner[y * r.w + x] : -1;
        };
        for (let y = 0; y < r.h; y++) {
          for (let x = 0; x < r.w; x++) {
            const id = owner[y * r.w + x];
            const right = at(x + 1, y);
            const down = at(x, y + 1);
            const isEdge = edge !== null && ((right >= 0 && right !== id) || (down >= 0 && down !== id));
            this.paint(r.x + x, r.y + y, isEdge ? edge : seeds[id][2]);
          }
        }
        return;
      }
      case 'leaves': {
        // Foliage brush: many small leaf stamps inside the current silhouette,
        // shaded from a ramp (dark → light) with light from the top-left of each
        // cluster; edge pixels lean dark, highlights land on top.
        const r = this.rectArgs(op);
        const ramp = (Array.isArray(op.colors) ? op.colors : []).map((c) => this.color(c));
        if (ramp.length < 3) throw new PixelError('leaves: colors en az 3 tonluk rampa olmalı (koyudan açığa).');
        const rand = mulberry32(int(op.seed, 'seed', 1));
        const density = op.density === undefined ? 0.7 : Math.max(0.05, Math.min(3, Number(op.density)));
        const inMask = new Uint8Array(this.c.w * this.c.h);
        // Default mask: the silhouette painted in the darkest ramp tone.
        if (!this.only) this.only = ramp[0] || 'opaque';
        let area = 0;
        for (let y = r.y; y < r.y + r.h; y++) {
          for (let x = r.x; x < r.x + r.w; x++) {
            if (x < 0 || y < 0 || x >= this.c.w || y >= this.c.h || !this.allowed(x, y)) continue;
            inMask[y * this.c.w + x] = 1;
            area++;
          }
        }
        this.only = null;
        const mask = (x, y) => x >= 0 && y >= 0 && x < this.c.w && y < this.c.h && inMask[y * this.c.w + x] === 1;
        // Leaf tips may poke out of the silhouette into empty pixels (ragged edge).
        const spill = op.spill !== false;
        const free = (x, y) => spill && x >= 0 && y >= 0 && x < this.c.w && y < this.c.h && this.c.get(x, y) === 0;
        const clusters = Array.isArray(op.clusters) && op.clusters.length ? op.clusters.map((c) => ({ cx: Number(c[0]), cy: Number(c[1]), r: Math.max(1, Number(c[2]) || 1) })) : [{ cx: r.x + r.w / 2, cy: r.y + r.h / 2, r: Math.max(r.w, r.h) / 2 }];
        const n = ramp.length;
        const shadeAt = (x, y) => {
          let best = clusters[0];
          let bestD = Infinity;
          for (const c of clusters) {
            const d = Math.hypot(x - c.cx, y - c.cy) / c.r;
            if (d < bestD) {
              bestD = d;
              best = c;
            }
          }
          // -1 (top-left, lit) … +1 (bottom-right, shade) inside the cluster
          const lx = (x - best.cx) / best.r;
          const ly = (y - best.cy) / best.r;
          const light = op.light === undefined ? (style === 'leaf' ? 0.55 : strokes ? 0.42 : 0.5) : Number(op.light);
          let t = light - 0.4 * (lx + ly) - 0.3 * Math.max(0, bestD - 0.75) + (rand() - 0.5) * 0.3;
          const edge = !mask(x - 1, y) || !mask(x + 1, y) || !mask(x, y - 1) || !mask(x, y + 1);
          if (edge) t -= 0.25;
          return Math.max(0, Math.min(n - 1, Math.round(t * (n - 1))));
        };
        // style "strokes" (default, crisp): short 2-3 px leaf strokes going from a
        // lit tip to a darker end, dark gaps left between them (Stardew-like).
        // style "clumps": rounder, softer leaf lumps.
        const STROKES = [
          [[0, 0, 1], [1, 0, 0], [2, 0, -1]],
          [[0, 0, 1], [1, 0, 0], [2, 1, -1]],
          [[0, 0, 1], [1, 1, 0], [2, 1, -1]],
          [[0, 1, 1], [1, 0, 0], [2, 0, -1]],
          [[0, 0, 1], [1, 0, 0], [1, 1, -1]],
          [[0, 0, 1], [0, 1, 0], [1, 1, -1]],
          [[0, 0, 0], [1, 0, -1]],
        ];
        const style = op.style === 'clumps' || op.style === 'strokes' ? op.style : 'leaf';
        const strokes = style === 'strokes';
        // Small pointed leaves (tip, body, shadow pixels under them).
        const SHAPES = [
          { body: [[2, 0], [1, 1], [2, 1], [0, 2], [1, 2]], hi: [[2, 0], [1, 1]], dark: [[0, 3], [1, 3], [2, 2]] },
          { body: [[0, 0], [0, 1], [1, 1], [1, 2], [2, 2]], hi: [[0, 0], [0, 1]], dark: [[0, 2], [1, 3], [2, 3]] },
          { body: [[1, 0], [0, 1], [1, 1], [2, 1], [1, 2]], hi: [[1, 0]], dark: [[0, 2], [2, 2], [1, 3]] },
          { body: [[0, 0], [1, 0], [1, 1], [2, 1]], hi: [[0, 0]], dark: [[0, 1], [1, 2], [2, 2]] },
          { body: [[0, 1], [1, 1], [1, 0], [2, 0]], hi: [[2, 0]], dark: [[0, 2], [1, 2]] },
        ];
        if (style === 'leaf') {
          this.leafStyle({ ramp, mask, free, shadeAt, rand, density, op, clusters });
          return;
        }
        const stamps = [];
        const count = Math.round((area * density) / 3);
        const points = [];
        for (let i = 0; i < this.c.w * this.c.h; i++) if (inMask[i]) points.push(i);
        for (let i = 0; i < count && points.length; i++) {
          const p = points[Math.floor(rand() * points.length)];
          const x = p % this.c.w;
          const y = Math.floor(p / this.c.w);
          stamps.push({ x, y, tone: shadeAt(x, y), shape: SHAPES[Math.floor(rand() * SHAPES.length)] });
        }
        // Dark leaves first, lit ones on top.
        stamps.sort((a, b) => a.tone - b.tone || a.y - b.y);
        const touches = (x, y) => mask(x - 1, y) || mask(x + 1, y) || mask(x, y - 1) || mask(x, y + 1);
        const put = (x, y, v, tip) => {
          if (mask(x, y) || (tip && free(x, y) && touches(x, y))) this.paint(x, y, v);
        };
        const flower = op.accent === undefined || op.accent === null ? null : this.color(op.accent, 'accent');
        const accentRate = Math.max(0, Math.min(0.5, Number(op.accent_rate) || 0.04));
        for (const s of stamps) {
          const t = s.tone;
          if (strokes) {
            const stroke = STROKES[Math.floor(rand() * STROKES.length)];
            for (const [dx, dy, dt] of stroke) {
              const tone = Math.max(0, Math.min(n - 1, t + dt));
              // Only dark tones spill out: a ragged, leafy edge instead of a hard outline.
              put(s.x + dx, s.y + dy, ramp[tone], tone <= 1);
            }
            if (flower && t >= 1 && rand() < accentRate) put(s.x, s.y, flower);
            continue;
          }
          for (const [dx, dy] of s.shape.dark) put(s.x + dx, s.y + dy, ramp[Math.max(0, t - 2)], false);
          for (const [dx, dy] of s.shape.body) put(s.x + dx, s.y + dy, ramp[t], true);
          if (t >= 2 && rand() < 0.6) for (const [dx, dy] of s.shape.hi) put(s.x + dx, s.y + dy, ramp[Math.min(n - 1, t + 1)], false);
          if (flower && t >= 1 && rand() < accentRate) put(s.x, s.y, flower);
        }
        return;
      }
      case 'foliage': {
        // Canopy built clump by clump from hand-drawn leaf sprites. Each clump
        // (back ones first) gets a dark bed, then leaves that point away from its
        // centre, lit from the top-left of that clump; front clumps overlap back
        // ones, so the crown reads as lumps of separate leaves.
        const ramp = (Array.isArray(op.colors) ? op.colors : []).map((c) => this.color(c));
        if (ramp.length !== 5) throw new PixelError('foliage: colors 5 tonluk rampa olmalı (en koyu boşluk, koyu kenar, orta, açık, parlak).');
        if (!Array.isArray(op.clusters) || !op.clusters.length) throw new PixelError('foliage: clusters [[cx,cy,r], ...] gerekli.');
        const rand = mulberry32(int(op.seed, 'seed', 1));
        const density = op.density === undefined ? 1 : Math.max(0.3, Math.min(3, Number(op.density)));
        const light = op.light === undefined ? 0 : Number(op.light);
        const flower = op.accent === undefined || op.accent === null ? null : this.color(op.accent, 'accent');
        const accentRate = Math.max(0, Math.min(0.6, Number(op.accent_rate) || 0));
        const clumps = op.clusters.map((c) => ({ cx: Number(c[0]), cy: Number(c[1]), r: Math.max(2, Number(c[2]) || 2) })).sort((a, b) => a.cy - b.cy || a.cx - b.cx);
        const allTop = Math.min(...clumps.map((c) => c.cy - c.r));
        const allBottom = Math.max(...clumps.map((c) => c.cy + c.r));
        for (const c of clumps) {
          // Lower clumps sit in the shade of the ones above.
          const depth = (c.cy - allTop) / Math.max(1, allBottom - allTop);
          const inside = (x, y) => (x + 0.5 - c.cx) ** 2 + (y + 0.5 - c.cy) ** 2 <= c.r * c.r;
          for (let y = Math.floor(c.cy - c.r); y <= c.cy + c.r; y++) for (let x = Math.floor(c.cx - c.r); x <= c.cx + c.r; x++) if (inside(x, y)) this.paint(x, y, ramp[0]);
          const spots = [];
          const step = Math.max(2, Math.round(3.4 / Math.sqrt(density)));
          for (let y = Math.floor(c.cy - c.r) - 1; y <= c.cy + c.r; y += step) {
            const shift = Math.floor(rand() * step);
            for (let x = Math.floor(c.cx - c.r) - 1 - shift; x <= c.cx + c.r; x += step) {
              const px = x + Math.floor(rand() * 2);
              const py = y + Math.floor(rand() * 2);
              const d = Math.hypot(px + 1.5 - c.cx, py + 1.5 - c.cy) / c.r;
              if (d > 1.02) continue;
              spots.push({ x: px, y: py, d });
            }
          }
          spots.sort((a, b) => a.y - b.y || a.x - b.x);
          for (const sp of spots) {
            const ax = (sp.x + 1.5 - c.cx) / c.r;
            const ay = (sp.y + 1.5 - c.cy) / c.r;
            const ang = Math.atan2(ay, ax) + (rand() - 0.5) * 0.9;
            let set;
            if (sp.d < 0.3) set = LEAF_SETS.center;
            else if (ang > -Math.PI / 4 && ang <= Math.PI / 4) set = LEAF_SETS.right;
            else if (ang > Math.PI / 4 && ang <= (3 * Math.PI) / 4) set = LEAF_SETS.down;
            else if (ang > -(3 * Math.PI) / 4 && ang <= -Math.PI / 4) set = LEAF_SETS.up;
            else set = LEAF_SETS.left;
            const leaf = set[Math.floor(rand() * set.length)];
            // tone shift: lit top-left of the clump +1, shaded bottom-right down to -2
            let shift = Math.round(-(ax + ay) * 0.9 - depth * 0.8 + light + (rand() - 0.5) * 0.6);
            shift = Math.max(-2, Math.min(1, shift));
            leaf.forEach((row, dy) => {
              [...row].forEach((ch, dx) => {
                if (ch === '.') return;
                const role = Number(ch);
                // rims and gaps keep their dark tones; the lit parts follow the clump's light
                const tone = role <= 1 ? role : Math.max(1, Math.min(4, role + shift));
                this.paint(sp.x + dx, sp.y + dy, ramp[tone]);
              });
            });
            if (flower && shift >= -1 && rand() < accentRate) this.paint(sp.x + 1, sp.y + 1, flower);
          }
        }
        return;
      }
      case 'replace': {
        const from = this.color(op.from, 'from');
        const to = this.color(op.to, 'to');
        const r = this.rectArgs(op);
        for (let y = r.y; y < r.y + r.h; y++) for (let x = r.x; x < r.x + r.w; x++) if (this.c.get(x, y) === from) this.c.set(x, y, to);
        return;
      }
      case 'mirror': {
        const axis = op.axis === 'y' ? 'y' : 'x';
        const keep = String(op.keep || (axis === 'x' ? 'left' : 'top'));
        const { w, h } = this.c;
        for (let y = 0; y < h; y++) {
          for (let x = 0; x < w; x++) {
            const mx = axis === 'x' ? w - 1 - x : x;
            const my = axis === 'y' ? h - 1 - y : y;
            const fromKept = axis === 'x' ? (keep === 'left' ? x < w / 2 : x >= w / 2) : keep === 'top' ? y < h / 2 : y >= h / 2;
            if (fromKept) this.c.set(mx, my, this.c.get(x, y));
          }
        }
        return;
      }
      case 'flip': {
        const src = this.c.clone();
        const { w, h } = this.c;
        for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) this.c.set(x, y, op.axis === 'y' ? src.get(x, h - 1 - y) : src.get(w - 1 - x, y));
        return;
      }
      case 'rotate': {
        const turns = ((int(op.turns, 'turns', 1) % 4) + 4) % 4;
        for (let t = 0; t < turns; t++) {
          const src = this.c.clone();
          const data = new Uint8Array(src.w * src.h);
          for (let y = 0; y < src.h; y++) for (let x = 0; x < src.w; x++) data[x * src.h + (src.h - 1 - y)] = src.get(x, y);
          this.c.w = src.h;
          this.c.h = src.w;
          this.c.data = data;
        }
        return;
      }
      case 'shift': {
        const dx = int(op.dx, 'dx', 0);
        const dy = int(op.dy, 'dy', 0);
        const wrap = op.wrap !== false;
        const src = this.c.clone();
        const { w, h } = this.c;
        for (let y = 0; y < h; y++) {
          for (let x = 0; x < w; x++) {
            let sx = x - dx;
            let sy = y - dy;
            if (wrap) {
              sx = ((sx % w) + w) % w;
              sy = ((sy % h) + h) % h;
            }
            this.c.set(x, y, src.get(sx, sy));
          }
        }
        return;
      }
      case 'outline': {
        // 1px outline in the transparent pixels around the art.
        const v = this.color(op.color);
        const corners = !!op.corners;
        const src = this.c.clone();
        for (let y = 0; y < src.h; y++) {
          for (let x = 0; x < src.w; x++) {
            if (src.get(x, y)) continue;
            let near = src.get(x - 1, y) || src.get(x + 1, y) || src.get(x, y - 1) || src.get(x, y + 1);
            if (!near && corners) near = src.get(x - 1, y - 1) || src.get(x + 1, y - 1) || src.get(x - 1, y + 1) || src.get(x + 1, y + 1);
            if (near) this.c.set(x, y, v);
          }
        }
        return;
      }
      case 'stamp': {
        if (!this.cwd) throw new PixelError('stamp burada kullanılamaz.');
        const src = load(this.cwd, checkName(String(op.source || '')));
        const sx = int(op.sx, 'sx', 0);
        const sy = int(op.sy, 'sy', 0);
        const sw = int(op.sw, 'sw', src.w - sx);
        const sh = int(op.sh, 'sh', src.h - sy);
        const x0 = int(op.x, 'x', 0);
        const y0 = int(op.y, 'y', 0);
        stampInto(this, src, { sx, sy, sw, sh, x0, y0, flip: op.flip, keepTransparent: op.transparent === true });
        return;
      }
      case 'palette_add':
        for (const c of Array.isArray(op.colors) ? op.colors : [op.color]) {
          const rgb = parseHex(String(c));
          if (!rgb) throw new PixelError(`palette_add: geçersiz renk ${c}`);
          this.c.slotFor(toHex(rgb), true);
        }
        return;
      case 'clear': {
        const v = op.color === undefined ? 0 : this.color(op.color);
        this.c.data.fill(v);
        return;
      }
      case 'selout': {
        // Selective outline: every silhouette pixel takes a darker shade of
        // the colour just inside it (1 step on the lit top/left, 2 elsewhere).
        const src = this.c.clone();
        const lit = op.light !== false;
        const edge = (x, y) => src.get(x, y) && (!src.get(x - 1, y) || !src.get(x + 1, y) || !src.get(x, y - 1) || !src.get(x, y + 1));
        for (let y = 0; y < src.h; y++) {
          for (let x = 0; x < src.w; x++) {
            if (!edge(x, y) || !this.allowed(x, y)) continue;
            const votes = new Map();
            for (let dy = -1; dy <= 1; dy++) {
              for (let dx = -1; dx <= 1; dx++) {
                const v = src.get(x + dx, y + dy);
                if (v && (dx || dy) && !edge(x + dx, y + dy) && !isTranslucent(src.rgb[v - 1])) votes.set(v, (votes.get(v) || 0) + 1);
              }
            }
            if (!votes.size) continue;
            let v = [...votes].sort((a, b) => b[1] - a[1])[0][0];
            const steps = lit && (!src.get(x, y - 1) || !src.get(x - 1, y)) ? 1 : 2;
            for (let i = 0; i < steps; i++) v = darker(this.c, v);
            this.c.set(x, y, v);
          }
        }
        return;
      }
      case 'ao': {
        // Ambient occlusion: pixels near the casters (wall foot, object base)
        // get darker, most at the contact, dithered at the far end.
        const from = new Set((Array.isArray(op.from) ? op.from : [op.from]).filter((c) => c !== undefined && c !== null).map((c) => this.color(c, 'from')));
        if (!from.size) throw new PixelError('ao: from (gölge düşüren renk/renkler) gerekli.');
        const depth = Math.max(1, Math.min(8, int(op.depth, 'depth', 3)));
        const strength = Math.max(1, Math.min(3, int(op.strength, 'strength', 1)));
        const down = (op.direction || 'down') === 'down';
        const src = this.c.clone();
        const dist = new Int16Array(src.w * src.h).fill(-1);
        const queue = [];
        for (let i = 0; i < src.data.length; i++) {
          if (from.has(src.data[i])) {
            dist[i] = 0;
            queue.push(i);
          }
        }
        for (let q = 0; q < queue.length; q++) {
          const i = queue[q];
          if (dist[i] >= depth) continue;
          const x = i % src.w;
          const y = (i / src.w) | 0;
          const next = down ? [[0, 1], [-1, 1], [1, 1]] : [[1, 0], [-1, 0], [0, 1], [0, -1]];
          for (const [dx, dy] of next) {
            const nx = x + dx;
            const ny = y + dy;
            if (nx < 0 || ny < 0 || nx >= src.w || ny >= src.h) continue;
            const j = ny * src.w + nx;
            if (dist[j] >= 0 || !src.data[j] || from.has(src.data[j])) continue;
            dist[j] = dist[i] + 1;
            queue.push(j);
          }
        }
        for (let i = 0; i < dist.length; i++) {
          if (dist[i] <= 0) continue;
          const x = i % src.w;
          const y = (i / src.w) | 0;
          if (!this.allowed(x, y)) continue;
          const f = ((depth - dist[i] + 1) / depth) * (strength + 1);
          let steps = Math.floor(f);
          if (f - steps >= 0.5 && (x + y) % 2 === 0) steps++;
          let v = src.data[i];
          for (let k = 0; k < steps; k++) v = darker(this.c, v);
          this.c.set(x, y, v);
        }
        return;
      }
      case 'rim': {
        // Rim light on the side facing the light, just inside an outline when there is one.
        const dirs = { 'top-left': [[0, -1], [-1, 0]], top: [[0, -1]], left: [[-1, 0]], 'top-right': [[0, -1], [1, 0]], right: [[1, 0]] };
        const side = dirs[op.side || 'top-left'];
        if (!side) throw new PixelError(`rim: side ${Object.keys(dirs).join(' | ')} olmalı.`);
        const src = this.c.clone();
        const isEdge = (x, y) => src.get(x, y) && (!src.get(x - 1, y) || !src.get(x + 1, y) || !src.get(x, y - 1) || !src.get(x, y + 1));
        let inset = op.inset;
        if (inset === undefined || inset === 'auto') {
          let e = 0;
          let en = 0;
          let n = 0;
          let nn = 0;
          for (let y = 0; y < src.h; y++) {
            for (let x = 0; x < src.w; x++) {
              const v = src.get(x, y);
              if (!v) continue;
              const l = luminance(src.rgb[v - 1]);
              if (isEdge(x, y)) {
                e += l;
                en++;
              } else {
                n += l;
                nn++;
              }
            }
          }
          inset = en && nn && n / nn - e / en > 40 ? 1 : 0;
        }
        inset = Number(inset) ? 1 : 0;
        const fixed = op.color === undefined ? null : this.color(op.color);
        const steps = Math.max(1, Math.min(3, int(op.steps, 'steps', 1)));
        const done = new Set();
        for (let y = 0; y < src.h; y++) {
          for (let x = 0; x < src.w; x++) {
            if (!src.get(x, y)) continue;
            for (const [dx, dy] of side) {
              if (src.get(x + dx, y + dy)) continue;
              const tx = x - dx * inset;
              const ty = y - dy * inset;
              const key = ty * src.w + tx;
              if (done.has(key) || !src.get(tx, ty) || (inset && isEdge(tx, ty)) || !this.allowed(tx, ty)) continue;
              done.add(key);
              let v = src.get(tx, ty);
              if (fixed !== null) v = fixed;
              else for (let k = 0; k < steps; k++) v = lighter(this.c, v);
              this.c.set(tx, ty, v);
            }
          }
        }
        return;
      }
      default:
        throw new PixelError(`Bilinmeyen işlem: "${op.op}". Olanlar: pixel, pixels, rect, line, circle, ellipse, polygon, fill, grid, noise, dither, voronoi, leaves, foliage, replace, mirror, flip, rotate, shift, outline, selout, ao, rim, stamp, palette_add, clear.`);
    }
  }
}

// Copies pixels from another canvas; colours missing from the target palette are added.
function stampInto(painter, src, { sx, sy, sw, sh, x0, y0, flip, keepTransparent }) {
  const map = new Map();
  for (let y = 0; y < sh; y++) {
    for (let x = 0; x < sw; x++) {
      const fx = flip === 'h' || flip === 'both' ? sw - 1 - x : x;
      const fy = flip === 'v' || flip === 'both' ? sh - 1 - y : y;
      const v = src.get(sx + fx, sy + fy);
      if (!v && !keepTransparent) continue;
      let t = 0;
      if (v) {
        if (!map.has(v)) map.set(v, painter.c.slotFor(src.palette[v - 1], true));
        t = map.get(v);
      }
      painter.paint(x0 + x, y0 + y, t);
    }
  }
}

// ---- tileset / map ----

// The colour one shade darker than `v` in the palette (for edge shading).
function darker(canvas, v, amount = 0.72) {
  if (!v) return 0;
  const c = canvas.rgb[v - 1];
  const target = c.map((x) => x * amount);
  let best = v;
  let bestD = Infinity;
  for (let i = 0; i < canvas.rgb.length; i++) {
    if (i + 1 === v || isTranslucent(canvas.rgb[i]) || luminance(canvas.rgb[i]) >= luminance(c)) continue;
    const d = dist2(target, canvas.rgb[i]);
    if (d < bestD) {
      bestD = d;
      best = i + 1;
    }
  }
  return best;
}

// The colour one shade lighter than `v` in the palette (rim light, highlights).
function lighter(canvas, v, amount = 0.3) {
  if (!v) return 0;
  const c = canvas.rgb[v - 1];
  const target = c.slice(0, 3).map((x) => x + (255 - x) * amount);
  let best = v;
  let bestD = Infinity;
  for (let i = 0; i < canvas.rgb.length; i++) {
    if (i + 1 === v || isTranslucent(canvas.rgb[i]) || luminance(canvas.rgb[i]) <= luminance(c)) continue;
    const d = dist2(target, canvas.rgb[i]);
    if (d < bestD) {
      bestD = d;
      best = i + 1;
    }
  }
  return best;
}

// 16 autotile variants of a base tile, laid out 4x4: variant index = bitmask of
// exposed sides (1 = top, 2 = right, 4 = bottom, 8 = left). Exposed sides get an
// outline row and a darker row inside it; corners between two exposed sides are cut.
function buildTileset(base, { outline = null, shade = true, round = true } = {}) {
  const tw = base.w;
  const th = base.h;
  const sheet = new Canvas(tw * 4, th * 4, base.palette);
  for (let mask = 0; mask < 16; mask++) {
    const ox = (mask % 4) * tw;
    const oy = Math.floor(mask / 4) * th;
    const top = mask & 1;
    const right = mask & 2;
    const bottom = mask & 4;
    const left = mask & 8;
    for (let y = 0; y < th; y++) {
      for (let x = 0; x < tw; x++) {
        let v = base.get(x, y);
        const edge = (top && y === 0) || (bottom && y === th - 1) || (left && x === 0) || (right && x === tw - 1);
        const inner = (top && y === 1) || (bottom && y === th - 2) || (left && x === 1) || (right && x === tw - 2);
        if (edge && outline) v = outline;
        else if (edge && shade) v = darker(base, darker(base, v));
        else if (inner && shade) v = darker(base, v);
        const cornerX = (left && x === 0) || (right && x === tw - 1);
        const cornerY = (top && y === 0) || (bottom && y === th - 1);
        if (round && cornerX && cornerY) v = 0;
        sheet.set(ox + x, oy + y, v);
      }
    }
  }
  return sheet;
}

// ---- 47-tile blob autotile from a 5-tile template (quarter composition) ----
// Port of HeartoLazor/autotile_generator (MIT). Template: 5 tiles in a row (more
// rows = variations): 1 fill (inside), 2 single (outer corners), 3 vertical
// (left/right edges), 4 horizontal (top/bottom edges), 5 inner corners. Every
// result tile is four quarters [TL, TR, BL, BR], each taken from one template
// tile; for a quarter the code follows from its horizontal neighbour h, vertical
// neighbour v and diagonal d: !h&&!v → 2, h&&!v → 4, !h&&v → 3, h&&v&&!d → 5, else 1.
// BLOB_LAYOUT is the generator's default map: Godot 3x3 minimal bitmask layout, 12x4.
const BLOB_LAYOUT = [
  [[2, 2, 3, 3], [2, 4, 3, 5], [4, 4, 5, 5], [4, 2, 5, 3], [1, 5, 5, 5], [4, 4, 5, 1], [4, 4, 1, 5], [5, 1, 5, 5], [2, 4, 3, 1], [5, 5, 1, 1], [4, 4, 1, 1], [4, 2, 1, 3]],
  [[3, 3, 3, 3], [3, 5, 3, 5], [5, 5, 5, 5], [5, 3, 5, 3], [3, 5, 3, 1], [5, 1, 1, 1], [1, 5, 1, 1], [5, 3, 1, 3], [3, 1, 3, 1], [5, 1, 1, 5], [0, 0, 0, 0], [1, 5, 1, 5]],
  [[3, 3, 2, 2], [3, 5, 2, 4], [5, 5, 4, 4], [5, 3, 4, 2], [3, 1, 3, 5], [1, 1, 5, 1], [1, 1, 1, 5], [1, 3, 5, 3], [5, 1, 5, 1], [1, 1, 1, 1], [1, 5, 5, 1], [1, 3, 1, 3]],
  [[2, 2, 2, 2], [2, 4, 2, 4], [4, 4, 4, 4], [4, 2, 4, 2], [5, 5, 1, 5], [5, 1, 4, 4], [1, 5, 4, 4], [5, 5, 5, 1], [3, 1, 2, 4], [1, 1, 4, 4], [1, 1, 5, 5], [1, 3, 4, 2]],
];

function quarterCode(h, v, d) {
  if (!h && !v) return 2;
  if (h && !v) return 4;
  if (!h && v) return 3;
  return d ? 1 : 5;
}

// Quarter codes [TL, TR, BL, BR] of a cell from its 8 neighbours (same(dx, dy) → bool).
function blobCodes(same) {
  return [
    quarterCode(same(-1, 0), same(0, -1), same(-1, -1)),
    quarterCode(same(1, 0), same(0, -1), same(1, -1)),
    quarterCode(same(-1, 0), same(0, 1), same(-1, 1)),
    quarterCode(same(1, 0), same(0, 1), same(1, 1)),
  ];
}

// Sheet kinds by shape: template 5x1 (or 5xN variations), blob 12x4, classic 4x4.
function sheetKind(c) {
  const t = c.w / 5;
  if (c.w !== c.h && Number.isInteger(t) && c.h % t === 0 && c.h / t <= 8) return { kind: 'template', tw: t };
  if (c.w * 4 === c.h * 12) return { kind: 'blob', tw: c.w / 12 };
  return { kind: 'mask16', tw: c.w / 4 };
}

// Where to copy quarter q of code c from: in a template, tile c-1 of a variation row;
// in a blob sheet, the first layout tile that has code c at quarter q.
function quarterSource(sheet, kind, tw, code, q, variation = 0) {
  const half = tw / 2;
  const qx = (q % 2) * half;
  const qy = Math.floor(q / 2) * half;
  if (kind === 'template') {
    const rows = Math.max(1, Math.floor(sheet.h / tw));
    return { sx: (code - 1) * tw + qx, sy: (variation % rows) * tw + qy };
  }
  for (let r = 0; r < BLOB_LAYOUT.length; r++) {
    for (let c = 0; c < BLOB_LAYOUT[r].length; c++) {
      if (BLOB_LAYOUT[r][c][q] === code) return { sx: c * tw + qx, sy: r * tw + qy };
    }
  }
  throw new PixelError(`Karo sayfasında ${code} kodlu çeyrek yok.`);
}

function drawQuarters(painter, sheet, kind, tw, codes, x0, y0, variation) {
  const half = tw / 2;
  codes.forEach((code, q) => {
    const { sx, sy } = quarterSource(sheet, kind, tw, code, q, variation);
    stampInto(painter, sheet, { sx, sy, sw: half, sh: half, x0: x0 + (q % 2) * half, y0: y0 + Math.floor(q / 2) * half, keepTransparent: false });
  });
}

// Template (5 tiles in a row, each tile size even) → 47-tile Godot blob sheet (12x4).
function buildBlobTileset(template, { variation = 0 } = {}) {
  const tw = template.w / 5;
  if (!Number.isInteger(tw) || tw < 4 || tw % 2) throw new PixelError('Şablon 5 karo yan yana olmalı, karo kenarı çift sayı (ör. 16 → 80x16).');
  const rows = Math.max(1, Math.floor(template.h / tw));
  if (template.h !== rows * tw) throw new PixelError(`Şablon yüksekliği karo boyunun katı olmalı (${tw}).`);
  const sheet = new Canvas(tw * 12, tw * 4, template.palette);
  const painter = new Painter(sheet);
  BLOB_LAYOUT.forEach((row, r) => row.forEach((codes, c) => {
    if (codes[0]) drawQuarters(painter, template, 'template', tw, codes, c * tw, r * tw, variation);
  }));
  return sheet;
}

// ---- Wave Function Collapse, overlapping model ----
// Port of mxgmn/WaveFunctionCollapse OverlappingModel (MIT, Maxim Gumin): learns every
// NxN pattern of a small sample (with rotations/reflections) and fills a bigger
// output so that every NxN window is a pattern of the sample. Good for organic
// textures and maps (cave floors, brick, roots, rivers) from a hand-drawn swatch.
function wfcOverlap(sample, { width, height, N = 3, periodicInput = true, periodic = true, symmetry = 8, seed = 1, tries = 10 } = {}) {
  const SX = sample.w;
  const SY = sample.h;
  const MX = int(width, 'width');
  const MY = int(height, 'height');
  checkSize(MX, MY);
  if (N < 2 || N > 5) throw new PixelError('N 2-5 olmalı.');
  if (SX < N || SY < N) throw new PixelError(`Örnek en az ${N}x${N} olmalı.`);
  const src = sample.data;
  const pattern = (f) => {
    const r = new Uint8Array(N * N);
    for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) r[x + y * N] = f(x, y);
    return r;
  };
  const rotate = (p) => pattern((x, y) => p[N - 1 - y + x * N]);
  const reflect = (p) => pattern((x, y) => p[N - 1 - x + y * N]);
  const index = new Map();
  const patterns = [];
  const weights = [];
  const xmax = periodicInput ? SX : SX - N + 1;
  const ymax = periodicInput ? SY : SY - N + 1;
  for (let y = 0; y < ymax; y++) {
    for (let x = 0; x < xmax; x++) {
      const ps = new Array(8);
      ps[0] = pattern((dx, dy) => src[((x + dx) % SX) + ((y + dy) % SY) * SX]);
      ps[1] = reflect(ps[0]);
      ps[2] = rotate(ps[0]);
      ps[3] = reflect(ps[2]);
      ps[4] = rotate(ps[2]);
      ps[5] = reflect(ps[4]);
      ps[6] = rotate(ps[4]);
      ps[7] = reflect(ps[6]);
      for (let k = 0; k < symmetry; k++) {
        const key = ps[k].join(',');
        const i = index.get(key);
        if (i !== undefined) weights[i]++;
        else {
          index.set(key, patterns.length);
          patterns.push(ps[k]);
          weights.push(1);
        }
      }
    }
  }
  const T = patterns.length;
  if (T > 4000) throw new PixelError(`Örnekte çok fazla desen var (${T}): daha küçük ya da daha az renkli örnek ver, N'i küçült.`);
  const DX = [-1, 0, 1, 0];
  const DY = [0, 1, 0, -1];
  const OPP = [2, 3, 0, 1];
  const agrees = (p1, p2, dx, dy) => {
    const xmin = dx < 0 ? 0 : dx;
    const xm = dx < 0 ? dx + N : N;
    const ymin = dy < 0 ? 0 : dy;
    const ym = dy < 0 ? dy + N : N;
    for (let y = ymin; y < ym; y++) for (let x = xmin; x < xm; x++) if (p1[x + N * y] !== p2[x - dx + N * (y - dy)]) return false;
    return true;
  };
  const propagator = [0, 1, 2, 3].map((d) => patterns.map((p1) => {
    const list = [];
    for (let t2 = 0; t2 < T; t2++) if (agrees(p1, patterns[t2], DX[d], DY[d])) list.push(t2);
    return Int32Array.from(list);
  }));
  const cells = MX * MY;
  if (cells * T > 6e6) throw new PixelError(`Çıktı × desen sayısı çok büyük (${MX}x${MY}, ${T} desen): çıktıyı küçült ya da örneği sadeleştir (N=2, daha az renk).`);
  const logW = weights.map((w) => w * Math.log(w));
  const sumW0 = weights.reduce((a, b) => a + b, 0);
  const sumWLogW0 = logW.reduce((a, b) => a + b, 0);
  const startEntropy = Math.log(sumW0) - sumWLogW0 / sumW0;
  const onBoundary = (x, y) => !periodic && (x + N > MX || y + N > MY);
  let wave;
  let compatible;
  let ones;
  let sumW;
  let sumWLogW;
  let entropy;
  let stack;
  let stackSize;
  const ban = (i, t) => {
    wave[i * T + t] = 0;
    const c = (i * T + t) * 4;
    compatible[c] = compatible[c + 1] = compatible[c + 2] = compatible[c + 3] = 0;
    stack[stackSize * 2] = i;
    stack[stackSize * 2 + 1] = t;
    stackSize++;
    ones[i]--;
    sumW[i] -= weights[t];
    sumWLogW[i] -= logW[t];
    entropy[i] = sumW[i] > 0 ? Math.log(sumW[i]) - sumWLogW[i] / sumW[i] : 0;
  };
  const propagate = () => {
    while (stackSize > 0) {
      stackSize--;
      const i1 = stack[stackSize * 2];
      const t1 = stack[stackSize * 2 + 1];
      const x1 = i1 % MX;
      const y1 = Math.floor(i1 / MX);
      for (let d = 0; d < 4; d++) {
        let x2 = x1 + DX[d];
        let y2 = y1 + DY[d];
        if (onBoundary(x2, y2) || (!periodic && (x2 < 0 || y2 < 0))) continue;
        x2 = (x2 + MX) % MX;
        y2 = (y2 + MY) % MY;
        const i2 = x2 + y2 * MX;
        const p = propagator[d][t1];
        for (let l = 0; l < p.length; l++) {
          const t2 = p[l];
          const c = (i2 * T + t2) * 4 + d;
          compatible[c]--;
          if (compatible[c] === 0) ban(i2, t2);
        }
      }
    }
    for (let i = 0; i < cells; i++) if (ones[i] <= 0) return false;
    return true;
  };
  const run = (rand) => {
    wave = new Uint8Array(cells * T).fill(1);
    compatible = new Int16Array(cells * T * 4);
    for (let i = 0; i < cells; i++) {
      for (let t = 0; t < T; t++) for (let d = 0; d < 4; d++) compatible[(i * T + t) * 4 + d] = propagator[OPP[d]][t].length;
    }
    ones = new Int32Array(cells).fill(T);
    sumW = new Float64Array(cells).fill(sumW0);
    sumWLogW = new Float64Array(cells).fill(sumWLogW0);
    entropy = new Float64Array(cells).fill(startEntropy);
    stack = new Int32Array(cells * T * 2);
    stackSize = 0;
    for (;;) {
      let argmin = -1;
      let min = Infinity;
      for (let i = 0; i < cells; i++) {
        if (onBoundary(i % MX, Math.floor(i / MX))) continue;
        if (ones[i] === 0) return null;
        if (ones[i] === 1) continue;
        const e = entropy[i] + 1e-6 * rand();
        if (e < min) {
          min = e;
          argmin = i;
        }
      }
      if (argmin < 0) break;
      let r = rand() * sumW[argmin];
      let chosen = -1;
      for (let t = 0; t < T; t++) {
        if (!wave[argmin * T + t]) continue;
        r -= weights[t];
        chosen = t;
        if (r <= 0) break;
      }
      for (let t = 0; t < T; t++) if (t !== chosen && wave[argmin * T + t]) ban(argmin, t);
      if (!propagate()) return null;
    }
    const observed = new Int32Array(cells);
    for (let i = 0; i < cells; i++) {
      observed[i] = -1;
      for (let t = 0; t < T; t++) if (wave[i * T + t]) { observed[i] = t; break; }
    }
    const out = new Canvas(MX, MY, sample.palette);
    for (let y = 0; y < MY; y++) {
      const dy = y < MY - N + 1 ? 0 : N - 1;
      for (let x = 0; x < MX; x++) {
        const dx = x < MX - N + 1 ? 0 : N - 1;
        const t = observed[x - dx + (y - dy) * MX];
        out.set(x, y, t < 0 ? 0 : patterns[t][dx + dy * N]);
      }
    }
    return out;
  };
  for (let k = 0; k < Math.max(1, tries); k++) {
    const out = run(mulberry32(seed + k * 7919));
    if (out) return { canvas: out, patterns: T, attempt: k + 1 };
  }
  throw new PixelError(`WFC ${tries} denemede çelişkiye düştü (${T} desen). N'i küçült, seed değiştir ya da örneği daha düzenli çiz.`);
}

// Tile reference "name" or "name#index" (index into a sheet split into tile-size cells).
function tileRef(cwd, ref, tw, th, cache) {
  const m = /^([A-Za-z0-9][A-Za-z0-9_-]{0,63})(?:#(\d+))?$/.exec(String(ref));
  if (!m) throw new PixelError(`Geçersiz karo: "${ref}" ("ad" ya da "ad#sıra").`);
  if (!cache.has(m[1])) cache.set(m[1], load(cwd, m[1]));
  const src = cache.get(m[1]);
  const index = m[2] === undefined ? 0 : Number(m[2]);
  const cols = Math.max(1, Math.floor(src.w / tw));
  const sx = (index % cols) * tw;
  const sy = Math.floor(index / cols) * th;
  if (sy + th > src.h) throw new PixelError(`"${ref}": sayfada o kadar karo yok.`);
  return { src, sx, sy };
}

function buildMap(cwd, { rows, tiles = {}, autotile = {}, base = null, tileSize, seed = 1, palette }) {
  if (!Array.isArray(rows) || !rows.length) throw new PixelError('rows gerekli: her karakter bir karo.');
  const cache = new Map();
  let tw = tileSize;
  if (!tw) {
    const first = Object.values(tiles).flat()[0] || Object.values(autotile)[0] || base;
    if (!first) throw new PixelError('tiles ya da autotile gerekli.');
    const ref = String(first).split('#')[0];
    const c = load(cwd, ref);
    tw = Object.values(autotile).includes(ref) ? sheetKind(c).tw : c.w;
  }
  tw = int(tw, 'tile_size');
  const th = tw;
  const width = Math.max(...rows.map((r) => [...String(r)].length));
  checkSize(width * tw, rows.length * th);
  const map = new Canvas(width * tw, rows.length * th, palette || []);
  const painter = new Painter(map, { cwd });
  const rand = mulberry32(seed);
  const grid = rows.map((r) => [...String(r)]);
  const at = (x, y) => (y >= 0 && y < grid.length && x >= 0 && x < grid[y].length ? grid[y][x] : null);
  for (let y = 0; y < grid.length; y++) {
    for (let x = 0; x < grid[y].length; x++) {
      const ch = grid[y][x];
      if (base) {
        // Ground under every cell, so cut autotile corners and sprites with holes show it.
        const under = tileRef(cwd, base, tw, th, cache);
        stampInto(painter, under.src, { sx: under.sx, sy: under.sy, sw: tw, sh: th, x0: x * tw, y0: y * th, keepTransparent: false });
      }
      if (ch === '.' && !tiles['.'] && !autotile['.']) continue;
      if (ch === ' ' && !tiles[' ']) continue;
      let ref;
      if (autotile[ch]) {
        // Map edges count as the same terrain (no outline along the border).
        const same = (nx, ny) => {
          const other = at(nx, ny);
          return other === null || other === ch;
        };
        const sheetName = String(autotile[ch]);
        if (!cache.has(sheetName)) cache.set(sheetName, load(cwd, checkName(sheetName)));
        const sheet = cache.get(sheetName);
        const { kind } = sheetKind(sheet);
        if (kind !== 'mask16') {
          // 8-neighbour blob: compose the cell from four quarters (template or 47-tile sheet).
          if (tw % 2) throw new PixelError('Blob autotile için karo kenarı çift olmalı.');
          const rowsOfVariations = kind === 'template' ? Math.max(1, Math.floor(sheet.h / tw)) : 1;
          const codes = blobCodes((dx, dy) => same(x + dx, y + dy));
          drawQuarters(painter, sheet, kind, tw, codes, x * tw, y * th, Math.floor(rand() * rowsOfVariations));
          continue;
        }
        const mask = (same(x, y - 1) ? 0 : 1) | (same(x + 1, y) ? 0 : 2) | (same(x, y + 1) ? 0 : 4) | (same(x - 1, y) ? 0 : 8);
        ref = `${sheetName}#${mask}`;
      } else if (tiles[ch] !== undefined) {
        const options = Array.isArray(tiles[ch]) ? tiles[ch] : [tiles[ch]];
        ref = options[Math.floor(rand() * options.length)];
      } else {
        throw new PixelError(`"${ch}" için karo tanımlı değil (tiles ya da autotile).`);
      }
      const { src, sx, sy } = tileRef(cwd, ref, tw, th, cache);
      stampInto(painter, src, { sx, sy, sw: tw, sh: th, x0: x * tw, y0: y * th, keepTransparent: false });
    }
  }
  return map;
}

// ---- reference image → pixel art ----

function medianCut(pixels, count) {
  let boxes = [pixels];
  while (boxes.length < count) {
    let bi = -1;
    let bestRange = -1;
    let bestCh = 0;
    boxes.forEach((box, i) => {
      if (box.length < 2) return;
      for (let ch = 0; ch < 3; ch++) {
        let lo = 255;
        let hi = 0;
        for (const p of box) {
          if (p[ch] < lo) lo = p[ch];
          if (p[ch] > hi) hi = p[ch];
        }
        if (hi - lo > bestRange) {
          bestRange = hi - lo;
          bi = i;
          bestCh = ch;
        }
      }
    });
    if (bi < 0 || bestRange <= 0) break;
    const box = boxes[bi].sort((a, b) => a[bestCh] - b[bestCh]);
    const mid = box.length >> 1;
    boxes.splice(bi, 1, box.slice(0, mid), box.slice(mid));
  }
  return boxes.map((box) => {
    const acc = [0, 0, 0];
    for (const p of box) for (let k = 0; k < 3; k++) acc[k] += p[k];
    return toHex(acc.map((v) => v / box.length));
  });
}

// background: "auto" (remove the colour connected to the corners), "keep", or a key colour (#ff00ff).
function removeBackground(img, background, tolerance) {
  const { w, h, data } = img;
  const alpha = new Uint8Array(w * h);
  for (let i = 0; i < w * h; i++) alpha[i] = data[i * 4 + 3] >= 128 ? 1 : 0;
  if (background === 'keep') return alpha;
  const tol = tolerance * tolerance * 9;
  const px = (i) => [data[i * 4], data[i * 4 + 1], data[i * 4 + 2]];
  const key = parseHex(String(background));
  if (key) {
    for (let i = 0; i < w * h; i++) if (dist2(px(i), key) <= tol) alpha[i] = 0;
    erodeFringe(alpha, w, h, px, [key], tol);
    return alpha;
  }
  const seen = new Uint8Array(w * h);
  const refs = [];
  for (const start of [0, w - 1, (h - 1) * w, h * w - 1]) {
    if (!alpha[start] || seen[start]) continue;
    const ref = px(start);
    refs.push(ref);
    const stack = [start];
    while (stack.length) {
      const i = stack.pop();
      if (seen[i]) continue;
      seen[i] = 1;
      if (!alpha[i] || dist2(px(i), ref) > tol) continue;
      alpha[i] = 0;
      const x = i % w;
      if (x > 0) stack.push(i - 1);
      if (x < w - 1) stack.push(i + 1);
      if (i >= w) stack.push(i - w);
      if (i < (h - 1) * w) stack.push(i + w);
    }
  }
  erodeFringe(alpha, w, h, px, refs, tol);
  return alpha;
}

// Anti-aliased edges are a blend of subject and background: peel off up to
// two rings of edge pixels that are still close to the background colour.
function erodeFringe(alpha, w, h, px, refs, tol) {
  if (!refs.length) return;
  const loose = tol * 6;
  for (let pass = 0; pass < 2; pass++) {
    const drop = [];
    for (let i = 0; i < w * h; i++) {
      if (!alpha[i]) continue;
      const x = i % w;
      const edge = (x > 0 && !alpha[i - 1]) || (x < w - 1 && !alpha[i + 1]) || (i >= w && !alpha[i - w]) || (i < (h - 1) * w && !alpha[i + w]);
      if (edge && refs.some((ref) => dist2(px(i), ref) <= loose)) drop.push(i);
    }
    for (const i of drop) alpha[i] = 0;
  }
}

function pixelize(img, opts) {
  const tolerance = opts.tolerance === undefined ? 40 : Number(opts.tolerance);
  let { w, h, data } = img;
  if (opts.grid > 1) {
    // The model drew "fat pixels": take the centre of each grid cell.
    const g = opts.grid;
    const nw = Math.floor(w / g);
    const nh = Math.floor(h / g);
    const nd = new Uint8Array(nw * nh * 4);
    for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) for (let k = 0; k < 4; k++) nd[(y * nw + x) * 4 + k] = data[((y * g + (g >> 1)) * w + x * g + (g >> 1)) * 4 + k];
    ({ w, h, data } = { w: nw, h: nh, data: nd });
  }
  const alpha = removeBackground({ w, h, data }, opts.background || 'auto', tolerance);
  let bx0 = 0;
  let by0 = 0;
  let bx1 = w;
  let by1 = h;
  if (opts.trim !== false && opts.background !== 'keep') {
    bx0 = w;
    by0 = h;
    bx1 = 0;
    by1 = 0;
    for (let y = 0; y < h; y++) {
      for (let x = 0; x < w; x++) {
        if (!alpha[y * w + x]) continue;
        if (x < bx0) bx0 = x;
        if (y < by0) by0 = y;
        if (x + 1 > bx1) bx1 = x + 1;
        if (y + 1 > by1) by1 = y + 1;
      }
    }
    if (bx1 <= bx0) throw new PixelError('Arka plan çıkarılınca görselde bir şey kalmadı (background: "keep" dene).');
  }
  const sw = bx1 - bx0;
  const sh = by1 - by0;
  let tw = opts.width ? int(opts.width, 'width') : 0;
  let th = opts.height ? int(opts.height, 'height') : 0;
  if (!tw && !th) tw = 32;
  if (!tw) tw = Math.max(1, Math.round((th * sw) / sh));
  if (!th) th = Math.max(1, Math.round((tw * sh) / sw));
  checkSize(tw, th);

  let palette;
  if (opts.palette === 'auto') {
    const sample = [];
    const step = Math.max(1, Math.floor((sw * sh) / 60000));
    for (let i = 0, n = 0; i < w * h; i++) {
      const x = i % w;
      const y = (i / w) | 0;
      if (x < bx0 || x >= bx1 || y < by0 || y >= by1 || !alpha[i]) continue;
      if (n++ % step === 0) sample.push([data[i * 4], data[i * 4 + 1], data[i * 4 + 2]]);
    }
    palette = resolvePalette(medianCut(sample, Math.max(2, Math.min(64, int(opts.colors, 'colors', 16)))));
  } else {
    palette = resolvePalette(opts.palette);
  }
  const canvas = new Canvas(tw, th, palette);
  // Room for the outline ring inside the requested size.
  const pad = opts.outline !== undefined && opts.outline !== null && opts.outline !== false && tw > 2 && th > 2 ? 1 : 0;
  const iw = tw - 2 * pad;
  const ih = th - 2 * pad;
  const average = opts.method === 'average';
  const snapCache = new Map();
  const snap = (r, g, b) => {
    const k = (r << 16) | (g << 8) | b;
    if (!snapCache.has(k)) snapCache.set(k, canvas.nearest([r, g, b]));
    return snapCache.get(k);
  };
  for (let y = 0; y < ih; y++) {
    const y0 = by0 + Math.floor((y * sh) / ih);
    const y1 = Math.max(y0 + 1, by0 + Math.floor(((y + 1) * sh) / ih));
    for (let x = 0; x < iw; x++) {
      const x0 = bx0 + Math.floor((x * sw) / iw);
      const x1 = Math.max(x0 + 1, bx0 + Math.floor(((x + 1) * sw) / iw));
      let opaque = 0;
      let total = 0;
      const votes = new Map();
      const acc = [0, 0, 0];
      for (let sy = y0; sy < y1; sy++) {
        for (let sx = x0; sx < x1; sx++) {
          const i = sy * w + sx;
          total++;
          if (!alpha[i]) continue;
          opaque++;
          const r = data[i * 4];
          const g = data[i * 4 + 1];
          const b = data[i * 4 + 2];
          if (average) {
            acc[0] += r;
            acc[1] += g;
            acc[2] += b;
          } else {
            const v = snap(r, g, b);
            votes.set(v, (votes.get(v) || 0) + 1);
          }
        }
      }
      if (opaque * 2 < total) continue;
      let v;
      if (average) {
        v = canvas.nearest(acc.map((a) => a / opaque));
      } else {
        let best = 0;
        for (const [k, n] of votes) {
          if (n > best) {
            best = n;
            v = k;
          }
        }
      }
      canvas.set(x + pad, y + pad, v);
    }
  }
  if (opts.clean !== false) cleanOrphans(canvas);
  if (opts.outline !== undefined && opts.outline !== null && opts.outline !== false) addOutline(canvas, opts.outline);
  return canvas;
}

// A clean 1px outline around the silhouette: the broken dark specks left on
// the edge by downsampling go first, then a continuous ring is drawn outside.
function addOutline(canvas, color) {
  const painter = new Painter(canvas);
  const v = painter.color(color === true ? canvas.palette.reduce((a, b) => (luminance(parseHex(b)) < luminance(parseHex(a)) ? b : a)) : color, 'outline');
  const dark = luminance(canvas.rgb[v - 1]) + 40;
  const src = canvas.clone();
  for (let y = 0; y < src.h; y++) {
    for (let x = 0; x < src.w; x++) {
      const c = src.get(x, y);
      if (!c || luminance(src.rgb[c - 1]) > dark) continue;
      const edge = !src.get(x - 1, y) || !src.get(x + 1, y) || !src.get(x, y - 1) || !src.get(x, y + 1);
      if (edge) canvas.set(x, y, 0);
    }
  }
  painter.apply({ op: 'outline', color: v - 1 });
}

// Lone pixels whose four neighbours all share another colour take that colour.
function cleanOrphans(canvas) {
  const src = canvas.clone();
  for (let y = 1; y < src.h - 1; y++) {
    for (let x = 1; x < src.w - 1; x++) {
      const v = src.get(x, y);
      const n = [src.get(x - 1, y), src.get(x + 1, y), src.get(x, y - 1), src.get(x, y + 1)];
      if (n.every((c) => c === n[0]) && n[0] !== v) canvas.set(x, y, n[0]);
    }
  }
}

// ---- colour science: OKLab / OKLCH ----

function srgbToLinear(c) {
  const v = c / 255;
  return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
}

function linearToSrgb(v) {
  const c = v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
  return c * 255;
}

function toOklab(rgb) {
  const r = srgbToLinear(rgb[0]);
  const g = srgbToLinear(rgb[1]);
  const b = srgbToLinear(rgb[2]);
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
  const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
  const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
  return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
}

// OKLab → sRGB 0-255 (unclamped; check inGamut).
function fromOklab([L, a, b]) {
  const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
  const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
  const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
  return [
    linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
    linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
    linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
  ];
}

function lchToRgb(L, C, hDeg) {
  const h = (hDeg * Math.PI) / 180;
  const inGamut = (rgb) => rgb.every((v) => v >= -0.5 && v <= 255.5);
  let rgb = fromOklab([L, C * Math.cos(h), C * Math.sin(h)]);
  if (inGamut(rgb)) return rgb;
  // Out of gamut: keep lightness and hue, lower the chroma.
  let lo = 0;
  let hi = C;
  for (let i = 0; i < 18; i++) {
    const mid = (lo + hi) / 2;
    const t = fromOklab([L, mid * Math.cos(h), mid * Math.sin(h)]);
    if (inGamut(t)) {
      lo = mid;
      rgb = t;
    } else {
      hi = mid;
    }
  }
  return inGamut(rgb) ? rgb : fromOklab([L, 0, 0]);
}

function oklch(rgb) {
  const [L, a, b] = toOklab(rgb);
  return { L, C: Math.hypot(a, b), h: ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360 };
}

// Turn hue `h` toward `target` by `amount` degrees along the shorter way.
function hueToward(h, target, amount) {
  let d = ((target - h + 540) % 360) - 180;
  if (Math.abs(d) < amount) return target;
  return (h + Math.sign(d) * amount + 360) % 360;
}

// A material ramp, dark → light, around a base colour: even lightness steps
// in OKLab, shadows turning cool (blue-violet), lights warm (yellow), chroma
// highest around the base.
function makeRamp(base, { steps = 7, hueShift = 1, dark = null, light = null } = {}) {
  const rgb = parseHex(String(base));
  if (!rgb) throw new PixelError(`Geçersiz renk: ${base}`);
  const n = Math.max(3, Math.min(12, Math.round(steps)));
  const shift = Math.max(0, Math.min(2, Number(hueShift)));
  const { L: L0, C: C0, h: h0 } = oklch(rgb);
  const lmin = dark === null ? Math.max(0.12, Math.min(L0 - 0.18, 0.24)) : Math.max(0.05, Math.min(L0 - 0.02, Number(dark)));
  const lmax = light === null ? Math.min(0.97, Math.max(L0 + 0.18, 0.9)) : Math.min(0.99, Math.max(L0 + 0.02, Number(light)));
  const k = Math.max(1, Math.min(n - 2, Math.round(((L0 - lmin) / Math.max(0.01, lmax - lmin)) * (n - 1))));
  const grey = C0 < 0.03;
  const out = [];
  for (let i = 0; i < n; i++) {
    let L;
    let t;
    if (i === k) {
      out.push(toHex(rgb));
      continue;
    }
    if (i < k) {
      t = -(k - i) / k;
      L = L0 + (lmin - L0) * (-t);
    } else {
      t = (i - k) / (n - 1 - k);
      L = L0 + (lmax - L0) * t;
    }
    const a = Math.abs(t);
    let h = grey ? (t < 0 ? 285 : 90) : t < 0 ? hueToward(h0, 285, 40 * shift * a) : hueToward(h0, 95, 30 * shift * a);
    let C = grey ? C0 + 0.025 * shift * a : t < 0 ? C0 * (1 - 0.3 * a) : C0 * (1 - 0.6 * a ** 1.3);
    if (!grey && t < 0 && a > 0.75) C *= 0.85;
    out.push(toHex(lchToRgb(L, Math.max(0, C), h)));
  }
  return out;
}

// ---- reading finished pixel art (PNG) ----

const MAX_ANALYSE_SIDE = 2048;

// A decoded image whose colours are already pixel art → canvas (no
// resampling). Fails when it has too many colours (photo / anti-aliased).
function canvasFromImage(img) {
  const { w, h, data } = img;
  if (w > MAX_ANALYSE_SIDE || h > MAX_ANALYSE_SIDE) throw new PixelError(`Görsel çok büyük (${w}x${h}); en fazla ${MAX_ANALYSE_SIDE} piksel.`);
  const palette = [];
  const index = new Map();
  const out = new Uint8Array(w * h);
  for (let i = 0; i < w * h; i++) {
    const a = data[i * 4 + 3];
    if (a < 16) continue;
    const rgb = [data[i * 4], data[i * 4 + 1], data[i * 4 + 2]];
    const hex = toHex(a >= 250 ? rgb : [...rgb, a]);
    let v = index.get(hex);
    if (v === undefined) {
      if (palette.length >= MAX_COLORS) throw new PixelError(`Görselde ${MAX_COLORS}'ten fazla renk var: pixel art değil (yumuşatılmış/büyütülmüş ya da fotoğraf). Büyütülmüş kopya yerine 1x dosyayı ver ya da önce pixel_from_image ile indir.`);
      palette.push(hex);
      v = palette.length;
      index.set(hex, v);
    }
    out[i] = v;
  }
  return new Canvas(w, h, palette.length ? palette : ['#000000'], out);
}

// A true-pixel image (e.g. pixel-art-fixer output) as a canvas with at most `colors`
// colours (median cut, alpha made binary). colors 0 = keep exact colours when ≤255.
function quantizeImage(img, colors = 0, { palette = null, background = 'keep', tolerance = 40 } = {}) {
  const { w, h } = img;
  const data = Buffer.from(img.data);
  if (background && background !== 'keep') {
    const alpha = removeBackground(img, background, tolerance);
    for (let i = 0; i < w * h; i++) if (!alpha[i]) data[i * 4 + 3] = 0;
  }
  const unique = new Set();
  const opaque = [];
  for (let i = 0; i < w * h; i++) {
    if (data[i * 4 + 3] < 128) continue;
    const p = [data[i * 4], data[i * 4 + 1], data[i * 4 + 2]];
    opaque.push(p);
    if (unique.size <= MAX_COLORS) unique.add(toHex(p));
  }
  if (!opaque.length) throw new PixelError('Görsel tamamen saydam.');
  const want = colors > 0 ? Math.min(colors, MAX_COLORS) : MAX_COLORS;
  let colours = palette;
  if (!colours && unique.size <= want) colours = [...unique];
  else if (!colours) {
    const step = Math.max(1, Math.floor(opaque.length / 40000));
    const sample = opaque.filter((_, i) => i % step === 0);
    colours = [...new Set(medianCut(sample, want))];
  }
  const canvas = new Canvas(w, h, colours);
  const memo = new Map();
  for (let i = 0; i < w * h; i++) {
    if (data[i * 4 + 3] < 128) continue;
    const key = (data[i * 4] << 16) | (data[i * 4 + 1] << 8) | data[i * 4 + 2];
    let v = memo.get(key);
    if (v === undefined) {
      v = canvas.nearest([data[i * 4], data[i * 4 + 1], data[i * 4 + 2]]);
      memo.set(key, v);
    }
    canvas.data[i] = v;
  }
  return canvas;
}

function cropCanvas(canvas, r) {
  const out = new Canvas(r.w, r.h, canvas.palette);
  for (let y = 0; y < r.h; y++) for (let x = 0; x < r.w; x++) out.set(x, y, canvas.get(r.x + x, r.y + y));
  return out;
}

// ---- quality report (pixel_lint) ----

function pct(n, total) {
  return `%${Math.round((100 * n) / Math.max(1, total))}`;
}

// Text report of the usual "looks artificial / amateur" signs, with
// coordinates, so a piece can be checked without looking at an image.
function lint(canvas, { tile = false } = {}) {
  const { w, h } = canvas;
  const solid = (v) => v && !isTranslucent(canvas.rgb[v - 1]);
  const at = (x, y) => canvas.get(x, y);
  let opaque = 0;
  const counts = new Map();
  for (let i = 0; i < canvas.data.length; i++) {
    const v = canvas.data[i];
    if (!solid(v)) continue;
    opaque++;
    counts.set(v, (counts.get(v) || 0) + 1);
  }
  const errors = [];
  const warns = [];
  const oks = [];
  if (!opaque) return 'Boş tuval: opak piksel yok.';
  // Silhouette pixels; for tiles the canvas border continues in the next tile.
  const border = (x, y) => x === 0 || y === 0 || x === w - 1 || y === h - 1;
  const edgeAt = (x, y) => solid(at(x, y)) && !(tile && border(x, y)) && (!at(x - 1, y) || !at(x + 1, y) || !at(x, y - 1) || !at(x, y + 1));
  const lum = (v) => luminance(canvas.rgb[v - 1]);

  // 1. Flat fills: the largest single-colour square and colour dominance.
  const sq = new Uint16Array(w * h);
  let best = { k: 0, x: 0, y: 0, v: 0 };
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      const v = at(x, y);
      if (!solid(v)) continue;
      let k = 1;
      if (x > 0 && y > 0 && at(x - 1, y) === v && at(x, y - 1) === v && at(x - 1, y - 1) === v) {
        k = 1 + Math.min(sq[y * w + x - 1], sq[(y - 1) * w + x], sq[(y - 1) * w + x - 1]);
      }
      sq[y * w + x] = k;
      if (k > best.k) best = { k, x: x - k + 1, y: y - k + 1, v };
    }
  }
  const side = Math.min(w, h);
  const flatLimit = side <= 16 ? 4 : side <= 32 ? 5 : side <= 64 ? 7 : 8;
  if (best.k >= flatLimit) {
    errors.push(`DÜZ DOLGU: ${best.k}x${best.k} tek renk blok ${canvas.palette[best.v - 1]} (x=${best.x}, y=${best.y}). Bu alana malzemenin ton dizisinden 2-4 ton, küme/doku/hacim ver (en fazla ${flatLimit - 1}x${flatLimit - 1} düz alan).`);
  } else {
    oks.push(`düz dolgu yok (en büyük tek renk kare ${best.k}x${best.k})`);
  }
  const [domV, domN] = [...counts].sort((a, b) => b[1] - a[1])[0];
  if (domN / opaque > 0.4 && counts.size > 2) errors.push(`TEK RENK BASKIN: ${canvas.palette[domV - 1]} opak piksellerin ${pct(domN, opaque)}'i. Ana malzemeyi 3+ tona dağıt.`);

  // 2. Material ramps: hue families (single linkage, so a hue-shifted ramp
  // stays one family), tone count and lightness steps.
  const info = [...counts].map(([v, n]) => ({ v, n, l: lum(v), c: oklch(canvas.rgb[v - 1]), lab: toOklab(canvas.rgb[v - 1]) }));
  const parent = info.map((_, i) => i);
  const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
  for (let i = 0; i < info.length; i++) {
    for (let j = i + 1; j < info.length; j++) {
      const a = info[i].c;
      const b = info[j].c;
      const greyA = a.C < 0.035;
      const greyB = b.C < 0.035;
      const near = greyA && greyB ? true : greyA || greyB ? false : Math.abs(((a.h - b.h + 540) % 360) - 180) < 40;
      if (near) parent[find(i)] = find(j);
    }
  }
  const groups = new Map();
  info.forEach((t, i) => {
    const r = find(i);
    if (!groups.has(r)) groups.set(r, []);
    groups.get(r).push(t);
  });
  const fams = [...groups.values()].map((tones) => {
    const n = tones.reduce((a, t) => a + t.n, 0);
    const main = tones.slice().sort((a, b) => b.n - a.n)[0];
    return { grey: main.c.C < 0.035, h: main.c.h, tones, n };
  });
  for (const f of fams.sort((a, b) => b.n - a.n)) {
    const share = f.n / opaque;
    if (share < 0.06) continue;
    f.tones.sort((a, b) => a.l - b.l);
    const label = `${f.grey ? 'gri/nötr' : `ton ~${Math.round(f.h)}°`} ailesi (${pct(f.n, opaque)}, ${f.tones.length} ton: ${f.tones.map((t) => canvas.palette[t.v - 1]).join(' ')})`;
    // Very dark families are outlines / cast shadows, not materials.
    const shadowOnly = f.tones.every((t) => t.l < 50);
    if (shadowOnly) continue;
    if (f.tones.length <= 2 && share >= 0.12) errors.push(`AZ TONLU MALZEME: ${label}. Böyle geniş bir malzemeye 5-8 tonluk dizi gerekir (pixel_ramp).`);
    else if (f.tones.length <= 3 && share >= 0.2) warns.push(`Az tonlu malzeme: ${label}; 5+ ton daha hacimli görünür.`);
    const close = [];
    const jumps = [];
    for (let i = 1; i < f.tones.length; i++) {
      const d = f.tones[i].l - f.tones[i - 1].l;
      const e = Math.hypot(...f.tones[i].lab.map((x, k) => x - f.tones[i - 1].lab[k]));
      if (e < 0.03) close.push(`${canvas.palette[f.tones[i - 1].v - 1]}~${canvas.palette[f.tones[i].v - 1]}`);
      if (d > 60) jumps.push(`${canvas.palette[f.tones[i - 1].v - 1]}→${canvas.palette[f.tones[i].v - 1]} (${Math.round(d)})`);
    }
    if (close.length) warns.push(`Neredeyse aynı tonlar: ${close.slice(0, 4).join(', ')} → birleştir ya da ayır.`);
    if (jumps.length) warns.push(`Büyük ton sıçraması (>60): ${jumps.slice(0, 4).join(', ')} → araya ton ekle (komşu tonlar arası ideal 15-35).`);
  }

  // 3. Outline: pure black / one flat colour.
  let edges = 0;
  let blackEdges = 0;
  const edgeColors = new Map();
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      if (!edgeAt(x, y)) continue;
      edges++;
      const v = at(x, y);
      const c = canvas.rgb[v - 1];
      if (luminance(c) < 34 && Math.max(...c.slice(0, 3)) - Math.min(...c.slice(0, 3)) < 24) blackEdges++;
      edgeColors.set(v, (edgeColors.get(v) || 0) + 1);
    }
  }
  if (edges >= 12) {
    const [topEdge, topEdgeN] = [...edgeColors].sort((a, b) => b[1] - a[1])[0];
    if (blackEdges / edges > 0.5) warns.push(`Siyah/nötr kontur: dış çizginin ${pct(blackEdges, edges)}'i saf koyu. Renkli kontur (selout işlemi) daha az "çıkartma" gibi durur.`);
    else if (topEdgeN / edges > 0.85 && edgeColors.size <= 2) warns.push(`Tek renk kontur (${canvas.palette[topEdge - 1]} ${pct(topEdgeN, edges)}): ışık tarafında daha açık, bölgeye göre renkli kontur (selout) dene.`);
    else oks.push('kontur renkli/bölgesel');
  }

  // 4. Light direction and pillow shading (rings inside the silhouette).
  if (edges >= 12 && opaque >= 64) {
    const dist = new Int16Array(w * h).fill(-1);
    const queue = [];
    for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (edgeAt(x, y)) {
      dist[y * w + x] = 0;
      queue.push(y * w + x);
    }
    for (let q = 0; q < queue.length; q++) {
      const i = queue[q];
      const x = i % w;
      const y = (i / w) | 0;
      for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
        const nx = x + dx;
        const ny = y + dy;
        if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
        const j = ny * w + nx;
        if (dist[j] >= 0 || !solid(canvas.data[j])) continue;
        dist[j] = dist[i] + 1;
        queue.push(j);
      }
    }
    let cx = 0;
    let cy = 0;
    for (let i = 0; i < w * h; i++) if (solid(canvas.data[i])) {
      cx += i % w;
      cy += (i / w) | 0;
    }
    cx /= opaque;
    cy /= opaque;
    const acc = { tl: [0, 0], br: [0, 0], core: [0, 0] };
    for (let i = 0; i < w * h; i++) {
      if (dist[i] < 1) continue;
      const x = i % w;
      const y = (i / w) | 0;
      const l = lum(canvas.data[i]);
      const key = dist[i] >= 4 ? 'core' : dist[i] <= 2 ? (x - cx + (y - cy) < 0 ? 'tl' : 'br') : null;
      if (!key) continue;
      acc[key][0] += l;
      acc[key][1]++;
    }
    const avg = (k) => (acc[k][1] ? acc[k][0] / acc[k][1] : null);
    const tl = avg('tl');
    const br = avg('br');
    const core = avg('core');
    if (tl !== null && br !== null) {
      if (core !== null && core - tl > 12 && core - br > 12 && Math.abs(tl - br) < 10) warns.push(`Yastık gölge (bilinçli değilse): kenarlar her yönden koyu (sol-üst ${Math.round(tl)}, sağ-alt ${Math.round(br)}, orta ${Math.round(core)}). Işığı tek yönden ver: sol-üst kenar açık, sağ-alt koyu; gölge şekli hacme göre, kontura göre değil.`);
      else if (Math.abs(tl - br) < 6) warns.push(`Işık yönü belirsiz (sol-üst kenar ${Math.round(tl)} ≈ sağ-alt ${Math.round(br)}): ışık tarafını açıp karşı tarafı koyulaştır.`);
      else if (br > tl + 6) warns.push(`Işık sağ-alttan geliyor gibi (sol-üst ${Math.round(tl)} < sağ-alt ${Math.round(br)}); projede ışık sol-üstten olmalı.`);
      else oks.push(`ışık sol-üstten (kenar parlaklığı ${Math.round(tl)} > ${Math.round(br)})`);
    }
  }

  // 5. Orphans (lone pixels unlike all 8 neighbours).
  const orphans = [];
  for (let y = 1; y < h - 1; y++) {
    for (let x = 1; x < w - 1; x++) {
      const v = at(x, y);
      if (!solid(v)) continue;
      let alone = true;
      for (let dy = -1; dy <= 1 && alone; dy++) for (let dx = -1; dx <= 1; dx++) if ((dx || dy) && at(x + dx, y + dy) === v) {
        alone = false;
        break;
      }
      if (alone && at(x - 1, y) && at(x + 1, y) && at(x, y - 1) && at(x, y + 1)) orphans.push([x, y]);
    }
  }
  if (orphans.length / opaque > 0.1) warns.push(`Yetim pikseller çok (${orphans.length}, ${pct(orphans.length, opaque)}): gürültü gibi görünür. Ör. ${orphans.slice(0, 8).map((p) => `(${p[0]},${p[1]})`).join(' ')}. Bilerek konan parıltılar dışında kümelere kat.`);
  else oks.push(`yetim piksel az (${orphans.length})`);

  // 6. Banding: 1px stripes of a middle tone running along the same contour.
  let bands = 0;
  const bandAt = [];
  for (let y = 1; y < h - 1; y++) {
    for (let x = 1; x < w - 1; x++) {
      const v = at(x, y);
      if (!solid(v)) continue;
      for (const [dx, dy, px, py] of [[1, 0, 0, 1], [0, 1, 1, 0]]) {
        const a = at(x - dx, y - dy);
        const b = at(x + dx, y + dy);
        if (!solid(a) || !solid(b) || a === v || b === v || a === b) continue;
        const la = lum(a);
        const lv = lum(v);
        const lb = lum(b);
        if (!((la < lv && lv < lb) || (la > lv && lv > lb))) continue;
        if (at(x + px, y + py) === v && at(x + px - dx, y + py - dy) === a && at(x + px + dx, y + py + dy) === b) {
          bands++;
          if (bandAt.length < 6) bandAt.push(`(${x},${y})`);
          break;
        }
      }
    }
  }
  if (bands / opaque > 0.05) warns.push(`Banding: ${bands} pikselde (${pct(bands, opaque)}) tonlar kontura paralel 1px şeritler halinde. Şeritleri kır: ton sınırlarını kaydır, kümeler halinde boya. Ör. ${bandAt.join(' ')}`);
  else oks.push('banding yok');

  // 7. Silhouette notches: 1px bumps/dents on the outer profile.
  if (!tile) {
    let notches = 0;
    let len = 0;
    const where = [];
    const profile = (get, n) => {
      const p = [];
      for (let i = 0; i < n; i++) p.push(get(i));
      for (let i = 1; i < p.length - 1; i++) {
        if (p[i - 1] === null || p[i] === null || p[i + 1] === null) continue;
        len++;
        const s1 = p[i] - p[i - 1];
        const s2 = p[i + 1] - p[i];
        if (Math.abs(s1) === 1 && Math.abs(s2) === 1 && s1 === -s2 && p[i - 1] === p[i + 1]) {
          notches++;
          if (where.length < 6) where.push(i);
        }
      }
    };
    const firstX = (y, dir) => {
      for (let k = 0; k < w; k++) {
        const x = dir > 0 ? k : w - 1 - k;
        if (solid(at(x, y))) return x;
      }
      return null;
    };
    const firstY = (x, dir) => {
      for (let k = 0; k < h; k++) {
        const y = dir > 0 ? k : h - 1 - k;
        if (solid(at(x, y))) return y;
      }
      return null;
    };
    profile((y) => firstX(y, 1), h);
    profile((y) => firstX(y, -1), h);
    profile((x) => firstY(x, 1), w);
    profile((x) => firstY(x, -1), w);
    if (len && notches / len > 0.08) warns.push(`Silüette çok 1px çentik/çıkıntı (${notches}): kenar titrek görünür; düzgün merdiven adımları kullan (1-1-2-2-3 gibi).`);
  }

  // 8. Tiles: the seam across the wrap should look like any other column.
  if (tile && w >= 4 && h >= 4) {
    const diff = (x1, y1, x2, y2) => {
      const a = at(x1, y1);
      const b = at(x2, y2);
      return a && b ? Math.abs(lum(a) - lum(b)) : 0;
    };
    let inH = 0;
    let seamH = 0;
    let inV = 0;
    let seamV = 0;
    for (let y = 0; y < h; y++) {
      for (let x = 0; x < w - 1; x++) inH += diff(x, y, x + 1, y);
      seamH += diff(w - 1, y, 0, y);
    }
    for (let x = 0; x < w; x++) {
      for (let y = 0; y < h - 1; y++) inV += diff(x, y, x, y + 1);
      seamV += diff(x, h - 1, x, 0);
    }
    const rh = seamH / h / Math.max(0.5, inH / (h * (w - 1)));
    const rv = seamV / w / Math.max(0.5, inV / (w * (h - 1)));
    const msg = `dikiş oranı yatay ${rh.toFixed(2)}, dikey ${rv.toFixed(2)} (1 civarı iyi, >1.5 belirgin)`;
    if (rh > 1.5 || rv > 1.5) errors.push(`KARO DİKİŞİ: ${msg}. Kenar sütun/satırlarını karşı kenarla uyumlu yap (shift wrap ile ortaya alıp düzelt).`);
    else oks.push(msg);
  }

  const lines = [`Kalite raporu: ${w}x${h}, ${opaque} opak piksel, ${counts.size} renk.`];
  for (const e of errors) lines.push(`✗ ${e}`);
  for (const m of warns) lines.push(`! ${m}`);
  if (oks.length) lines.push(`✓ ${oks.join('; ')}`);
  lines.push(errors.length ? `Sonuç: ${errors.length} hata, ${warns.length} uyarı → göstermeden önce düzelt.` : warns.length ? `Sonuç: hata yok, ${warns.length} uyarı (bilinçli değilse düzelt).` : 'Sonuç: sorun bulunmadı.');
  return lines.join('\n');
}

// ---- remap a hi-res concept onto material ramps (portrait technique) ----

function quantile(sorted, q) {
  if (!sorted.length) return 0;
  const i = Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))));
  return sorted[i];
}

// Downsamples a hi-res image cell by cell; each cell picks its material (the
// ramp nearest in hue) and a tone from the local light (median pushed toward
// p20 in shadow, p85 in light: crisp volume), mapped over the whole ramp.
function remap(img, { width, height, ramps, regions = [], background = 'auto', tolerance = 40, outline = true, contrast = 0.6, spread = 0.35, clean = true } = {}) {
  if (!ramps || typeof ramps !== 'object' || Array.isArray(ramps) || !Object.keys(ramps).length) throw new PixelError('ramps gerekli: {"sac": ["#2c2040", ...], "ten": [...]} (koyudan açığa, her biri 3+ ton).');
  const mats = Object.entries(ramps).map(([name, list]) => {
    const tones = resolvePalette(list);
    if (tones.length < 3) throw new PixelError(`ramps.${name}: en az 3 ton gerekli.`);
    const labs = tones.map((t) => toOklab(parseHex(t)));
    return { name, tones, labs };
  });
  const { w, h, data } = img;
  const alpha = removeBackground(img, background, Number(tolerance));
  let bx0 = w;
  let by0 = h;
  let bx1 = 0;
  let by1 = 0;
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (alpha[y * w + x]) {
    if (x < bx0) bx0 = x;
    if (y < by0) by0 = y;
    if (x + 1 > bx1) bx1 = x + 1;
    if (y + 1 > by1) by1 = y + 1;
  }
  if (background === 'keep') {
    bx0 = 0;
    by0 = 0;
    bx1 = w;
    by1 = h;
  }
  if (bx1 <= bx0) throw new PixelError('Arka plan çıkarılınca görselde bir şey kalmadı (background: "keep" dene).');
  const sw = bx1 - bx0;
  const sh = by1 - by0;
  let tw = width ? int(width, 'width') : 0;
  let th = height ? int(height, 'height') : 0;
  if (!tw && !th) tw = 64;
  if (!tw) tw = Math.max(1, Math.round((th * sw) / sh));
  if (!th) th = Math.max(1, Math.round((tw * sh) / sw));
  checkSize(tw, th);
  const forced = new Int16Array(tw * th).fill(-1);
  for (const r of Array.isArray(regions) ? regions : []) {
    const mi = mats.findIndex((m) => m.name === r.material);
    if (mi < 0) throw new PixelError(`regions: "${r.material}" ramps içinde yok.`);
    const rx = int(r.x, 'x', 0);
    const ry = int(r.y, 'y', 0);
    const rw = int(r.w, 'w', tw - rx);
    const rh = int(r.h, 'h', th - ry);
    for (let y = Math.max(0, ry); y < Math.min(th, ry + rh); y++) for (let x = Math.max(0, rx); x < Math.min(tw, rx + rw); x++) forced[y * tw + x] = mi;
  }
  const cell = new Array(tw * th).fill(null);
  for (let y = 0; y < th; y++) {
    const y0 = by0 + Math.floor((y * sh) / th);
    const y1 = Math.max(y0 + 1, by0 + Math.floor(((y + 1) * sh) / th));
    for (let x = 0; x < tw; x++) {
      const x0 = bx0 + Math.floor((x * sw) / tw);
      const x1 = Math.max(x0 + 1, bx0 + Math.floor(((x + 1) * sw) / tw));
      const Ls = [];
      let a = 0;
      let b = 0;
      let total = 0;
      for (let sy = y0; sy < y1; sy++) {
        for (let sx = x0; sx < x1; sx++) {
          const i = sy * w + sx;
          total++;
          if (!alpha[i]) continue;
          const lab = toOklab([data[i * 4], data[i * 4 + 1], data[i * 4 + 2]]);
          Ls.push(lab[0]);
          a += lab[1];
          b += lab[2];
        }
      }
      if (Ls.length * 2 < total) continue;
      Ls.sort((p, q) => p - q);
      a /= Ls.length;
      b /= Ls.length;
      const p50 = quantile(Ls, 0.5);
      let mi = forced[y * tw + x];
      if (mi < 0) {
        let bestD = Infinity;
        mats.forEach((m, k) => {
          for (const t of m.labs) {
            const d = (t[1] - a) ** 2 + (t[2] - b) ** 2 + 0.12 * (t[0] - p50) ** 2;
            if (d < bestD) {
              bestD = d;
              mi = k;
            }
          }
        });
      }
      cell[y * tw + x] = { mi, p20: quantile(Ls, 0.2), p50, p85: quantile(Ls, 0.85) };
    }
  }
  // Per-material lightness range in the image → spread over the whole ramp.
  // spread blends a linear mapping with the material's own rank order
  // (histogram equalisation), so a mostly-light material still uses its
  // darker tones for volume.
  const sortedVals = mats.map((_, k) => cell.filter((c) => c && c.mi === k).map((c) => c.p50).sort((p, q) => p - q));
  const range = sortedVals.map((vals) => (vals.length ? [quantile(vals, 0.03), quantile(vals, 0.97)] : [0, 1]));
  const rankOf = (vals, v) => {
    let lo = 0;
    let hi = vals.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (vals[mid] < v) lo = mid + 1;
      else hi = mid;
    }
    return vals.length > 1 ? lo / (vals.length - 1) : 0.5;
  };
  const eqFor = mats.map((m) => {
    const v = spread && typeof spread === 'object' ? (spread[m.name] === undefined ? 0.35 : spread[m.name]) : spread;
    return Math.max(0, Math.min(1, Number(v) || 0));
  });
  const palette = [];
  for (const m of mats) for (const t of m.tones) if (!palette.includes(t)) palette.push(t);
  const canvas = new Canvas(tw, th, palette);
  const solidAt = (x, y) => x >= 0 && y >= 0 && x < tw && y < th && !!cell[y * tw + x];
  const usedTones = mats.map(() => new Set());
  for (let y = 0; y < th; y++) {
    for (let x = 0; x < tw; x++) {
      const c = cell[y * tw + x];
      if (!c) continue;
      const m = mats[c.mi];
      const edge = !solidAt(x - 1, y) || !solidAt(x + 1, y) || !solidAt(x, y - 1) || !solidAt(x, y + 1);
      let tone;
      if (outline && edge) {
        tone = m.tones[0];
      } else {
        let sum = 0;
        let n = 0;
        for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
          const o = solidAt(x + dx, y + dy) ? cell[(y + dy) * tw + x + dx] : null;
          if (o && o.mi === c.mi) {
            sum += o.p50;
            n++;
          }
        }
        const local = sum / Math.max(1, n);
        const value = c.p50 + Number(contrast) * (c.p50 < local ? c.p20 - c.p50 : c.p85 - c.p50);
        const [lo, hi] = range[c.mi];
        const linear = Math.max(0, Math.min(1, (value - lo) / Math.max(0.02, hi - lo)));
        const eq = eqFor[c.mi];
        const t = Math.max(0, Math.min(1, (1 - eq) * linear + eq * rankOf(sortedVals[c.mi], value)));
        const inner = outline && m.tones.length >= 4 ? m.tones.slice(1) : m.tones;
        tone = inner[Math.round(t * (inner.length - 1))];
      }
      usedTones[c.mi].add(tone);
      canvas.set(x, y, palette.indexOf(tone) + 1);
    }
  }
  if (clean) cleanOrphans(canvas);
  const counts = mats.map((_, k) => cell.filter((c) => c && c.mi === k).length);
  const report = mats.map((m, k) => `${m.name}: ${counts[k]} piksel, ${usedTones[k].size}/${m.tones.length} ton`).join('; ');
  return { canvas, report };
}

// ---- character identity (consistency between frames) ----

// frames: [{ label, canvas }]. identity: { parts: {eyes: [hex...]}, palette?, height? }.
function characterCheck(identity, frames) {
  const parts = Object.entries(identity.parts || {}).map(([name, list]) => [name, new Set(resolvePalette(list))]);
  const allowed = new Set(identity.palette ? resolvePalette(identity.palette) : []);
  for (const [, set] of parts) for (const c of set) allowed.add(c);
  const rows = frames.map(({ label, canvas }) => {
    let x0 = canvas.w;
    let y0 = canvas.h;
    let x1 = -1;
    let y1 = -1;
    const counts = Object.fromEntries(parts.map(([n]) => [n, 0]));
    const foreign = new Map();
    for (let y = 0; y < canvas.h; y++) {
      for (let x = 0; x < canvas.w; x++) {
        const v = canvas.get(x, y);
        if (!v) continue;
        const hex = canvas.palette[v - 1];
        if (isTranslucent(canvas.rgb[v - 1])) continue;
        if (x < x0) x0 = x;
        if (y < y0) y0 = y;
        if (x > x1) x1 = x;
        if (y > y1) y1 = y;
        for (const [n, set] of parts) if (set.has(hex)) counts[n]++;
        if (identity.palette && !allowed.has(hex)) foreign.set(hex, (foreign.get(hex) || 0) + 1);
      }
    }
    return { label, empty: x1 < 0, w: x1 - x0 + 1, h: y1 - y0 + 1, counts, foreign };
  });
  const live = rows.filter((r) => !r.empty);
  if (!live.length) return 'Karelerin hepsi boş.';
  const median = (vals) => {
    const s = vals.slice().sort((a, b) => a - b);
    return s[s.length >> 1];
  };
  const mh = identity.height || median(live.map((r) => r.h));
  const issues = [];
  const lines = [];
  for (const r of live) {
    const notes = [];
    if (Math.abs(r.h - mh) > 2) notes.push(`boy ${r.h} (beklenen ~${mh})`);
    for (const [n] of parts) {
      const m = median(live.map((o) => o.counts[n]));
      const c = r.counts[n];
      if (m > 0 && c === 0) notes.push(`${n} YOK`);
      else if (m >= 1 && Math.abs(c - m) >= 2 && (c > m * 1.5 || c < m * 0.5)) notes.push(`${n} ${c} px (diğerleri ~${m}: ${c > m ? 'büyük' : 'küçük'})`);
    }
    if (r.foreign.size) notes.push(`palet dışı renk: ${[...r.foreign].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([hex, n]) => `${hex}×${n}`).join(' ')}`);
    if (notes.length) issues.push(`✗ ${r.label}: ${notes.join('; ')}`);
    lines.push(`${r.label}: ${r.w}x${r.h}, ${parts.map(([n]) => `${n} ${r.counts[n]}`).join(', ')}`);
  }
  return [`Karakter tutarlılığı: ${live.length} kare.`, ...(issues.length ? issues : ['✓ kareler tutarlı (boy, parça renkleri ve boyutları, palet).']), 'Kareler:', ...lines].join('\n');
}

// Splits a sprite sheet into frames of fw x fh (empty cells are dropped).
function splitSheet(canvas, fw, fh) {
  const out = [];
  for (let y = 0; y + fh <= canvas.h; y += fh) {
    for (let x = 0; x + fw <= canvas.w; x += fw) {
      const c = cropCanvas(canvas, { x, y, w: fw, h: fh });
      if (c.data.some((v) => v)) out.push({ label: `kare ${out.length} (x=${x}, y=${y})`, canvas: c });
    }
  }
  return out;
}

// ---- tile variants ----

// Variants of a seamless tile that keep its border (so they still join each
// other): the inside is shifted with wrap and sometimes mirrored. Returns a
// one-row sheet (base first) and a 3x3 test map of random variants.
function tileVariants(base, { variants = 3, border = 2, seed = 1 } = {}) {
  const n = Math.max(1, Math.min(6, variants));
  const b = Math.max(1, Math.min(Math.floor(Math.min(base.w, base.h) / 4), border));
  const iw = base.w - 2 * b;
  const ih = base.h - 2 * b;
  const rand = mulberry32(seed);
  const list = [base];
  for (let k = 0; k < n; k++) {
    const v = base.clone();
    const dx = 1 + Math.floor(rand() * Math.max(1, iw - 1));
    const dy = 1 + Math.floor(rand() * Math.max(1, ih - 1));
    const flip = rand() < 0.5;
    for (let y = 0; y < ih; y++) {
      for (let x = 0; x < iw; x++) {
        let sx = (x + dx) % iw;
        const sy = (y + dy) % ih;
        if (flip) sx = iw - 1 - sx;
        v.set(b + x, b + y, base.get(b + sx, b + sy));
      }
    }
    list.push(v);
  }
  const sheet = new Canvas(base.w * list.length, base.h, base.palette);
  list.forEach((t, i) => {
    for (let y = 0; y < t.h; y++) for (let x = 0; x < t.w; x++) sheet.set(i * base.w + x, y, t.get(x, y));
  });
  const map = new Canvas(base.w * 3, base.h * 3, base.palette);
  for (let ty = 0; ty < 3; ty++) {
    for (let tx = 0; tx < 3; tx++) {
      const t = list[Math.floor(rand() * list.length)];
      for (let y = 0; y < t.h; y++) for (let x = 0; x < t.w; x++) map.set(tx * base.w + x, ty * base.h + y, t.get(x, y));
    }
  }
  return { sheet, map, count: list.length };
}

// ---- animation ----

// Wind: rows above `pivot` slide sideways by whole pixels (more at the top,
// as a wave travelling down), and a few leaf pixels flutter between their
// neighbouring tones each frame. No resampling, so every frame stays crisp.
function windFrames(base, { frames = 6, strength = 1, pivot = null, top = null, flutter = 0.04, colors = null, seed = 1 } = {}) {
  const n = Math.max(2, Math.min(24, frames));
  let first = base.h;
  let last = 0;
  for (let y = 0; y < base.h; y++) {
    for (let x = 0; x < base.w; x++) {
      if (base.get(x, y)) {
        first = Math.min(first, y);
        last = Math.max(last, y);
      }
    }
  }
  const y0 = top === null ? first : top;
  const py = pivot === null ? Math.round(first + (last - first) * 0.55) : pivot;
  // Tones that may flutter: the given colours (dark → light) or none.
  const ramp = Array.isArray(colors) ? colors.map((c) => base.palette.indexOf(toHex(parseHex(String(c)) || [0, 0, 0])) + 1).filter((v) => v > 0) : [];
  const out = [];
  for (let f = 0; f < n; f++) {
    const phase = (2 * Math.PI * f) / n;
    const frame = new Canvas(base.w, base.h, base.palette);
    for (let y = 0; y < base.h; y++) {
      const reach = y >= py ? 0 : Math.min(1, (py - y) / Math.max(1, py - y0));
      const dx = Math.round(strength * reach * Math.sin(phase - (y - y0) * 0.12));
      for (let x = 0; x < base.w; x++) frame.set(x, y, base.get(x - dx, y));
    }
    if (ramp.length > 1 && flutter > 0) {
      const rand = mulberry32(seed * 7919 + f);
      for (let i = 0; i < frame.data.length; i++) {
        const k = ramp.indexOf(frame.data[i]);
        if (k < 0 || rand() >= flutter) continue;
        const to = k + (rand() < 0.5 ? -1 : 1);
        if (to >= 1 && to < ramp.length) frame.data[i] = ramp[to];
      }
    }
    out.push(frame);
  }
  return out;
}

function sheetOf(frames) {
  const w = frames[0].w;
  const h = frames[0].h;
  const sheet = new Canvas(w * frames.length, h, frames[0].palette);
  frames.forEach((fr, i) => {
    for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) sheet.set(i * w + x, y, fr.get(x, y));
  });
  return sheet;
}

function lzwEncode(indices, minCode) {
  const clear = 1 << minCode;
  const eoi = clear + 1;
  let dict = new Map();
  let next = eoi + 1;
  let size = minCode + 1;
  const bytes = [];
  let cur = 0;
  let bits = 0;
  const write = (code) => {
    cur |= code << bits;
    bits += size;
    while (bits >= 8) {
      bytes.push(cur & 0xff);
      cur >>>= 8;
      bits -= 8;
    }
  };
  write(clear);
  let prefix = indices[0];
  for (let i = 1; i < indices.length; i++) {
    const k = indices[i];
    const key = prefix * 4096 + k;
    if (dict.has(key)) {
      prefix = dict.get(key);
      continue;
    }
    write(prefix);
    if (next < 4096) {
      dict.set(key, next++);
      if (next > 1 << size && size < 12) size++;
    } else {
      write(clear);
      dict = new Map();
      next = eoi + 1;
      size = minCode + 1;
    }
    prefix = k;
  }
  write(prefix);
  write(eoi);
  if (bits > 0) bytes.push(cur & 0xff);
  return Buffer.from(bytes);
}

// Looping GIF. Translucent palette colours are blended over `background`
// when one is given; without it they become transparent (GIF has no alpha).
function encodeGIF(frames, { scale = 1, delay = 120, background = null } = {}) {
  const base = frames[0];
  const bg = background ? parseHex(background) : null;
  const colors = [[0, 0, 0]];
  const map = [0];
  for (const c of base.rgb) {
    let rgb = c.slice(0, 3);
    if (isTranslucent(c)) {
      if (!bg) {
        map.push(0);
        continue;
      }
      const a = c[3] / 255;
      rgb = [0, 1, 2].map((k) => Math.round(c[k] * a + bg[k] * (1 - a)));
    }
    colors.push(rgb);
    map.push(colors.length - 1);
  }
  if (bg) colors[0] = bg.slice(0, 3);
  let bitsPer = 1;
  while (1 << bitsPer < colors.length) bitsPer++;
  const tableSize = 1 << bitsPer;
  const W = base.w * scale;
  const H = base.h * scale;
  const parts = [Buffer.from('GIF89a', 'ascii')];
  const lsd = Buffer.alloc(7);
  lsd.writeUInt16LE(W, 0);
  lsd.writeUInt16LE(H, 2);
  lsd[4] = 0x80 | ((bitsPer - 1) << 4) | (bitsPer - 1);
  parts.push(lsd);
  const table = Buffer.alloc(tableSize * 3);
  colors.forEach((c, i) => table.set(c, i * 3));
  parts.push(table);
  parts.push(Buffer.from([0x21, 0xff, 0x0b, ...Buffer.from('NETSCAPE2.0', 'ascii'), 0x03, 0x01, 0x00, 0x00, 0x00]));
  const cs = Math.max(1, Math.round(delay / 10));
  for (const fr of frames) {
    // disposal 2 (restore to background) so transparent pixels do not keep old frames
    parts.push(Buffer.from([0x21, 0xf9, 0x04, bg ? 0x08 : 0x09, cs & 0xff, cs >> 8, 0x00, 0x00]));
    const id = Buffer.alloc(10);
    id[0] = 0x2c;
    id.writeUInt16LE(W, 5);
    id.writeUInt16LE(H, 7);
    parts.push(id);
    const idx = new Uint8Array(W * H);
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) idx[y * W + x] = map[fr.get(Math.floor(x / scale), Math.floor(y / scale))];
    const minCode = Math.max(2, bitsPer);
    const data = lzwEncode(idx, minCode);
    parts.push(Buffer.from([minCode]));
    for (let i = 0; i < data.length; i += 255) {
      const chunk = data.subarray(i, i + 255);
      parts.push(Buffer.from([chunk.length]), chunk);
    }
    parts.push(Buffer.from([0x00]));
  }
  parts.push(Buffer.from([0x3b]));
  return Buffer.concat(parts);
}

const GUIDE = `Pixel art rehberi (Agent Web). Hedef: Stardew/profesyonel kalite. Düz tek renk dolgu, siyah kontur, "çıkartma gibi" yapıştırılmış görünüm YOK.

A. İŞ AKIŞI
1. Hazırlık: boyut (karo 16/32, eşya 16-32, karakter sprite 32-64, portre 64, ağaç 32-64, bina 48-128; harita = karolardan). Işık HER ZAMAN sol-üstten. Projede karakter kimliği (pixel_character show) ya da tools/pixelkit.py varsa önce onları kullan.
2. Malzeme ton dizileri: her malzemeye pixel_ramp ile ayrı dizi (geniş malzeme 6-9 ton, küçük detay 4-5; komşu tonlar arası parlaklık farkı 15-35; gölge soğuk mor-maviye, ışık sıcak sarıya kayar). Hazır paletten rastgele renk seçme; bir sprite'ta 16-40 renk normaldir. Başka oyunlardan renk kopyalama.
3. Yöntem:
   a) Portre / ince detay: gemini_image ile yüksek çözünürlüklü taslak (C) → pixel_remap (malzeme dizileri; spread: ten 0.1-0.2, saç/kumaş 0.4-0.6, metal 0.4) → göz, iris, kirpik, ağız, burun, parıltı ELLE (pixel_draw grid/pixels ya da Python'da satır satır piksel listesi) → pixel_lint.
   b) Yaratık / obje / animasyon: Python + pixelkit (Sprite.shade ile hacim, selout, contact_shadow, highlight, rows ile elle blok; kareleri fonksiyonla üret) ya da pixel_draw. Kod hacmi kurar, kritik pikseller (göz, parıltı, kenar) elle yazılır. 1x PNG kaydet (art/ ya da gorseller/ altına; canlı panelde görünür) + büyütülmüş önizleme.
   c) Karo / çevre: düşük kontrastlı 4-6 tonlu doku (noise/voronoi wrap:true, kümeler), gömülü taşlar, pixel_tilecheck (dikiş + varyasyonlar), pixel_tileset autotile, pixel_map; objeler pixel_draw stamp ile. Organik doku/yerleşim için küçük elle çizilmiş örnek + pixel_wfc (her NxN pencere örnekten gelir, tekrar etmez, palet korunur).
   d) Hazır pixel art stili görsel (gemini_image "pixel art, 32x32 sprite, limited palette" ya da büyütülmüş/JPEG pixel art): pixel_fix gerçek ızgarayı bulur, her hücreyi tek piksel yapar (pixel_from_image'dan çok daha doğru). Sonra colors/palette ile palet kilidi, pixel_lint, elle rötuş.
4. Kontrol: her parçada pixel_lint (tuval adı ya da PNG yolu; sprite sayfası için frame:{w,h}). Her ✗ düzeltilmeden gösterilmez. Karakter karelerinde pixel_character check. Görsele (pixel_view) yalnızca son kontrolde bak: görsel pahalıdır, lint ucuzdur.
5. Teslim: pixel_export ya da share_file (oyuna 1x PNG, göstermek için büyütülmüş). Kısaca neyi düzelttiğini ve kalan zayıf noktayı dürüstçe söyle.

B. KALİTE KURALLARI
1. DÜZ DOLGU YASAK: hiçbir malzeme tek renkle boyanmaz. En büyük tek renk alan: 16px işte ≤3x3, 32px'te ≤4x4, 64px'te ≤6x6. Geniş alanlar mikro kümelerden oluşur: 2-3 px'lik sırt (açık) → yamaç (orta) → oluk (koyu); saç tutamları, kumaş kıvrımları, taş yumruları tek tek yontulur.
2. Renkli seçici kontur (selout): saf siyah dış çizgi yok. Her bölgenin konturu kendi en koyu tonu (saç → koyu mor-lacivert, ten → koyu bordo, metal → koyu çelik, jel → koyu çam yeşili), ışık tarafında bir ton açık; iç konturlar (tutam arası, göz kapağı, kıvrım) bir kademe daha açık. pixel_draw selout ya da pixelkit selout.
3. Hacim: ışık sol-üst; gölge forma göre şekillenir. Kontura paralel koyu halka (yastık gölge) ve kontura paralel 1px ton şeritleri (banding) yasak. Malzeme farkı: metal = yüksek kontrast + keskin parıltı + perçin/pah + alt yansıma; kumaş = yumuşak kıvrım kümeleri; deri = orta kontrast, kenar ışığı; jel/su = iç gölge + kenar kırılması + ıslak parıltı + kabarcık, iç çekirdek; taş = üst üste binen yumrular, aşınmış pahlar, çatlak; ahşap = lif çizgisi + koyu oyuk + çivi.
4. Yere oturtma ve atmosfer: nesne havada durmaz (yarı saydam elips gölge #rrggbbaa, ayak/kök yayılması, alt kısımda koyulaşma); duvar dipleri, nesne arkaları, kapı girintileri ambient occlusion (pixel_draw ao / pixelkit ao); ışık kaynakları (meşale, fener) çevresine 2-3 halkalı sıcak hale; ışığın sol-üst kenara vurduğu yerde rim (pixel_draw rim).
5. Çevre/karo: tek karonun kopyası ızgara gibi görünür → varyasyonlar (pixel_tilecheck) ve çok karolu desenler; geçişler kare basamak değil, yuvarlatılmış kenar + etrafa dağılmış küçük taş/toprak kümeleri; zemin dokusu düşük kontrastlı (komşu ton farkı 8-20), üstündeki objeler daha kontrastlı (okunurluk); tuzak/çukur zeminle kaynaşır, "yama" gibi durmaz.
6. Çizgi ve detay: tek ölçekte tek piksel yoğunluğu; çizgilerde düzenli merdiven (1-1-2-2-3), silüette 1px çentik/çıkıntı yok; yetim tek pikseller yalnız bilinçli parıltı.
7. Animasyon: aynı palet ve oranlar (pixel_character check: boy, göz boyutu/rengi kareler arasında sabit); ön hazırlık, squash-stretch, takip (follow-through), ikincil hareket (saç, atkı, damlacık). Saldırı izi (smear): çekirdek beyaz → açık → enerji rengi → koyu sönüm + kıvılcım pikselleri.

C. TASLAK GÖRSEL (gemini_image): "flat cel-shaded illustration, limited palette (max 24 colours), no gradients, no blur, no noise texture, clear readable silhouette, strong light from top-left, solid flat magenta #ff00ff background" + transparent:true. Karakterde önce cephe portresi, sonra onu files ile referans vererek diğer açılar/kareler. Taslağı olduğu gibi küçültme: pixel_remap ile malzeme dizilerine eşle, sonra elle rötuş.

D. ÖZ DENETİM (göstermeden önce, sormadan, en fazla 3 tur): pixel_lint'te ✗ kalmamalı; uyarıları bilinçli değilse düzelt. Sonra bir kez pixel_view (stats:true): tekrar eden desen, kusursuz geometrik silüet, tek tip ışık, havada duran nesne; referans varsa aynı ölçekte ton oranı, renk sayısı, detay boyutu karşılaştırması. Ton dağılımı kabaca: en koyu %25-35, koyu %25-35, orta %15-20, açık %8-12, parlak ≤%5.

E. ARAÇ İPUÇLARI
- Yapraklık (ağaç tacı, çalı): foliage {colors:[5 ton: en koyu boşluk, koyu kenar, orta, açık, parlak], clusters:[[cx,cy,r],...] (8-12 farklı boyda topak), density ~1.1, light -0.5…0.3}. Gövde/kök grid ile elle; kökler kısa, asimetrik, yere yayılır; önce yarı saydam gölge, sonra gövde.
- Dokular: çim/toprak = noise (2-4 ton, density 0.2-0.5, üst üste); taş = voronoi (wrap:true, edge = harç); su = yatay dither şeritleri + parıltı; tahta = yatay lif + noise.
- Autotile: en iyi sonuç = elle çizilmiş 5 karoluk şablon (dolgu, tek ada, dikey, yatay, iç köşeler; yan yana, kenar çift sayı) → pixel_tileset 47'lik blob sayfası (Godot düzeni) ya da şablonu doğrudan pixel_map autotile'a ver (8 komşu, çeyrek karolar; ek satırlar varyasyon). Tek karodan hızlı yol: pixel_tileset 16'lık (maske 1 üst, 2 sağ, 4 alt, 8 sol). pixel_map base ile zemin altta.
- Kural kitabı: pixel_rules (62 dosya: malzeme, karakter, yüz, el, animasyon, ağaç, su, zemin, karo, mimari, VFX, UI, sahne, "yapay görüntü izleri"). Çizmeden önce konunun dosyasını oku; bitirmeden önce 07-review-checklist + 92-generated-art-tells + topic "critic" ile bağımsız eleştiri. Lospec paletleri: pixel_rules topic "palettes" (ara), palette: "lospec:<anahtar>".
- Animasyon: pixel_animate wind (taç satırları tam piksel kayar, colors ile yaprak kıpırtısı) → sprite sayfası + GIF.
- Canlı izleme: kullanıcı yan menüdeki "🎨 Pixel art (canlı)" panelinde pixel_* tuvallerini her adımda, betiklerin kaydettiği PNG/GIF'leri her kayıtta görür. Ara adımlarda pixel_draw preview:false kullan.
- pixel_view: grid:8, region ile yakınlaştırma, ascii:true tam koordinat.
İşlemler (pixel_draw ops): pixel, pixels, rect, line, circle, ellipse, polygon, fill, grid (metin ızgarası + legend: en güvenilir şekil çizme yolu), noise, dither, voronoi, foliage, leaves, replace, mirror, flip, rotate, shift, outline, selout, ao, rim, stamp (başka tuvalden kopya), palette_add, clear. Her işleme "only": "opaque" | "transparent" | renk eklenebilir. Çağrıya symmetry: "x" | "y" | "both" verilirse her vuruş aynalanır.`;

module.exports = {
  DIR,
  MAX_SIDE,
  MAX_OPS,
  PALETTES,
  GUIDE,
  PixelError,
  Canvas,
  Painter,
  parseHex,
  toHex,
  resolvePalette,
  checkName,
  checkSize,
  load,
  save,
  list,
  encodePNG,
  decodeImage,
  imageType,
  thumbnail,
  render,
  autoScale,
  previewImage,
  asciiView,
  toneStats,
  buildTileset,
  buildBlobTileset,
  sheetKind,
  buildMap,
  wfcOverlap,
  lospecPalettes,
  findPalettes,
  quantizeImage,
  pixelize,
  makeRamp,
  oklch,
  canvasFromImage,
  cropCanvas,
  lint,
  remap,
  characterCheck,
  splitSheet,
  tileVariants,
  windFrames,
  sheetOf,
  encodeGIF,
};