Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sculpt_face_set.cc « sculpt_paint « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a9af1d46a487b07d3368ec2f792532a0fc736a34 (plain)
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
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
/* SPDX-License-Identifier: GPL-2.0-or-later
 * Copyright 2020 Blender Foundation. All rights reserved. */

/** \file
 * \ingroup edsculpt
 */

#include "MEM_guardedalloc.h"

#include "BLI_blenlib.h"
#include "BLI_compiler_attrs.h"
#include "BLI_hash.h"
#include "BLI_math.h"
#include "BLI_smallhash.h"
#include "BLI_task.h"
#include "BLI_vector.hh"

#include "DNA_brush_types.h"
#include "DNA_customdata_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"

#include "BKE_attribute.h"
#include "BKE_attribute.hh"
#include "BKE_brush.h"
#include "BKE_ccg.h"
#include "BKE_colortools.h"
#include "BKE_context.h"
#include "BKE_customdata.h"
#include "BKE_mesh.h"
#include "BKE_mesh_fair.h"
#include "BKE_mesh_mapping.h"
#include "BKE_mesh_types.h"
#include "BKE_multires.h"
#include "BKE_node.h"
#include "BKE_object.h"
#include "BKE_paint.h"
#include "BKE_pbvh.h"
#include "BKE_scene.h"
#include "BKE_subdiv_ccg.h"

#include "DEG_depsgraph.h"

#include "WM_api.h"
#include "WM_types.h"

#include "ED_sculpt.h"

#include "sculpt_intern.h"

#include "RNA_access.h"
#include "RNA_define.h"

#include "bmesh.h"
#include "bmesh_log.h"

#include <math.h>
#include <stdlib.h>

using blender::Vector;

static int sculpt_face_material_get(SculptSession *ss, PBVHFaceRef face)
{
  switch (BKE_pbvh_type(ss->pbvh)) {
    case PBVH_BMESH: {
      BMFace *f = (BMFace *)face.i;
      return f->mat_nr;
    }
    case PBVH_GRIDS:
    case PBVH_FACES:
      return ss->material_index[face.i];
  }

  return -1;
}

int SCULPT_face_set_get(SculptSession *ss, PBVHFaceRef face)
{
  switch (BKE_pbvh_type(ss->pbvh)) {
    case PBVH_BMESH: {
      BMFace *f = (BMFace *)face.i;
      return BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset);
    }
    case PBVH_GRIDS:
    case PBVH_FACES:
      return ss->face_sets[face.i];
  }
  return -1;
}

// returns previous face set
int SCULPT_face_set_set(SculptSession *ss, PBVHFaceRef face, int fset)
{
  int ret = 0;

  switch (BKE_pbvh_type(ss->pbvh)) {
    case PBVH_BMESH: {
      BMFace *f = (BMFace *)face.i;
      ret = BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset);

      BM_ELEM_CD_SET_INT(f, ss->cd_faceset_offset, fset);
      break;
    }
    case PBVH_FACES:
    case PBVH_GRIDS:
      ret = ss->face_sets[face.i];
      ss->face_sets[face.i] = fset;
      break;
  }

  return ret;
}

void SCULPT_face_check_origdata(SculptSession *ss, PBVHFaceRef face)
{
  if (!ss->attrs.orig_fsets) {
    return;
  }

  short *s = (short *)BKE_sculpt_face_attr_get(face, ss->attrs.orig_fsets);

  // pack ss->stroke_id in higher 16 bits
  if (s[1] != ss->stroke_id) {
    s[0] = SCULPT_face_set_get(ss, face);
    s[1] = ss->stroke_id;
  }
}

int SCULPT_face_set_original_get(SculptSession *ss, PBVHFaceRef face)
{
  if (!ss->attrs.orig_fsets) {
    return SCULPT_face_set_get(ss, face);
  }

  short *s = (short *)BKE_sculpt_face_attr_get(face, ss->attrs.orig_fsets);

  if (s[1] != ss->stroke_id) {
    s[0] = SCULPT_face_set_get(ss, face);
    s[1] = ss->stroke_id;
  }

  return s[0];
}

void SCULPT_face_ensure_original(SculptSession *ss, Object *ob)
{
  SculptAttributeParams params = {0};

  ss->attrs.orig_fsets = BKE_sculpt_attribute_ensure(
      ob, ATTR_DOMAIN_FACE, CD_PROP_INT32, SCULPT_ATTRIBUTE_NAME(orig_fsets), &params);
}

bool SCULPT_face_select_get(SculptSession *ss, PBVHFaceRef face)
{
  if (ss->bm) {
    BMFace *f = (BMFace *)face.i;

    return f->head.hflag & BM_ELEM_SELECT;
  }
  else {
    return ss->select_poly ? ss->select_poly[face.i] : false;
  }
}

/* Utils. */

int ED_sculpt_face_sets_find_next_available_id(struct Mesh *mesh)
{
  const int *face_sets = static_cast<const int *>(
      CustomData_get_layer_named(&mesh->pdata, CD_PROP_INT32, ".sculpt_face_set"));
  if (!face_sets) {
    return SCULPT_FACE_SET_NONE;
  }

  int next_face_set_id = 0;
  for (int i = 0; i < mesh->totpoly; i++) {
    next_face_set_id = max_ii(next_face_set_id, abs(face_sets[i]));
  }
  next_face_set_id++;

  return next_face_set_id;
}

void ED_sculpt_face_sets_initialize_none_to_id(struct Mesh *mesh, const int new_id)
{
  int *face_sets = static_cast<int *>(
      CustomData_get_layer_named(&mesh->pdata, CD_PROP_INT32, ".sculpt_face_set"));
  if (!face_sets) {
    return;
  }

  for (int i = 0; i < mesh->totpoly; i++) {
    if (face_sets[i] == SCULPT_FACE_SET_NONE) {
      face_sets[i] = new_id;
    }
  }
}

int ED_sculpt_face_sets_active_update_and_get(bContext *C, Object *ob, const float mval[2])
{
  SculptSession *ss = ob->sculpt;
  if (!ss) {
    return SCULPT_FACE_SET_NONE;
  }

  SculptCursorGeometryInfo gi;
  if (!SCULPT_cursor_geometry_info_update(C, &gi, mval, false, false)) {
    return SCULPT_FACE_SET_NONE;
  }

  return SCULPT_active_face_set_get(ss);
}

static BMesh *sculpt_faceset_bm_begin(Object *ob, SculptSession *ss, Mesh *mesh)
{
  if (ss->bm) {
    return ss->bm;
  }

  BMeshCreateParams params = {0};
  params.use_toolflags = true;

  const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(mesh);
  BMesh *bm = BM_mesh_create(&allocsize, &params);

  BMeshFromMeshParams cparams = {0};

  cparams.calc_face_normal = true;
  cparams.active_shapekey = ob->shapenr;
  cparams.use_shapekey = true;
  cparams.create_shapekey_layers = true;

  BM_mesh_bm_from_me(NULL, bm, mesh, &cparams);
  return bm;
}

static void sculpt_faceset_bm_end(SculptSession *ss, BMesh *bm)
{
  if (bm != ss->bm) {
    BM_mesh_free(bm);
  }
}

/* Draw Face Sets Brush. */

static int new_fset_apply_curve(SculptSession *ss,
                                SculptFaceSetDrawData *data,
                                int new_fset,
                                float poly_center[3],
                                float no[3],
                                SculptBrushTest *test,
                                BrushChannel *curve_ch,
                                int count)
{
  float fade2;
  float tmp[3];
  float n[3];

  sub_v3_v3v3(tmp, poly_center, test->location);

  cross_v3_v3v3(n, no, data->stroke_direction);
  normalize_v3(n);

  // find t along brush line
  float t = dot_v3v3(data->stroke_direction, tmp) / ss->cache->radius;
  CLAMP(t, -1.0f, 1.0f);
  t = t * 0.5 + 0.5;

  // find start and end points;
  float start[3], end[3];
  copy_v3_v3(start, ss->cache->last_location);
  copy_v3_v3(end, ss->cache->location);

  madd_v3_v3fl(start, data->prev_stroke_direction, 0.5f * ss->cache->radius);
  madd_v3_v3fl(end, data->next_stroke_direction, 0.5f * ss->cache->radius);

  float co[3];

  // interpolate direction and pos across stroke line
  float dir[3];
  if (t < 0.5) {
    interp_v3_v3v3(co, start, test->location, t * 2.0f);
    interp_v3_v3v3(dir, data->prev_stroke_direction, data->stroke_direction, t * 2.0f);
  }
  else {
    interp_v3_v3v3(co, test->location, end, (t - 0.5f) * 2.0f);
    interp_v3_v3v3(dir, data->stroke_direction, data->next_stroke_direction, (t - 0.5f) * 2.0f);
  }

  sub_v3_v3v3(tmp, poly_center, co);
  normalize_v3(dir);

  // get final distance from stroke curve
  cross_v3_v3v3(n, no, dir);
  normalize_v3(n);

  fade2 = fabsf(dot_v3v3(n, tmp)) / ss->cache->radius;
  CLAMP(fade2, 0.0f, 1.0f);

  fade2 = BKE_brush_channel_curve_evaluate(curve_ch, fade2, 1.0f);

  new_fset += (int)((1.0f - fade2) * (float)count);

  return new_fset;
}

ATTR_NO_OPT void do_draw_face_sets_brush_task_cb_ex(void *__restrict userdata,
                                                    const int n,
                                                    const TaskParallelTLS *__restrict tls)
{
  SculptFaceSetDrawData *data = (SculptFaceSetDrawData *)userdata;
  SculptSession *ss = data->ob->sculpt;
  const Brush *brush = data->brush;
  const float bstrength = data->bstrength;

  const bool use_fset_strength = data->use_fset_strength;
  const bool use_fset_curve = data->use_fset_curve;
  const int count = data->count;
  const int active_fset = data->faceset;
  BrushChannel *curve_ch = data->curve_ch;

  PBVHVertexIter vd;

  SculptBrushTest test;
  SculptBrushTestFn sculpt_brush_test_sq_fn = SCULPT_brush_test_init(
      ss, &test, (eBrushFalloffShape)data->brush->falloff_shape);

  const int thread_id = BLI_task_parallel_thread_id(tls);

  MVert *mvert = SCULPT_mesh_deformed_mverts_get(ss);
  const float test_limit = 0.05f;
  int cd_mask = -1;

  if (ss->bm) {
    cd_mask = CustomData_get_offset(&ss->bm->vdata, CD_PAINT_MASK);
  }

  /*check if we need to sample the current face set*/

  bool set_active_faceset = ss->cache->automasking &&
                            (ss->cache->automasking->settings.flags & BRUSH_AUTOMASKING_FACE_SETS);
  set_active_faceset = set_active_faceset && ss->cache->invert;
  set_active_faceset = set_active_faceset && ss->cache->automasking->settings.initial_face_set ==
                                                 ss->cache->automasking->settings.current_face_set;

  int automasking_fset_flag = 0;

  if (set_active_faceset) {
    // temporarily clear faceset flag
    automasking_fset_flag = ss->cache->automasking ? ss->cache->automasking->settings.flags &
                                                         BRUSH_AUTOMASKING_FACE_SETS :
                                                     0;
    ss->cache->automasking->settings.flags &= ~BRUSH_AUTOMASKING_FACE_SETS;
  }

  bool modified = false;

  AutomaskingNodeData automask_data;
  SCULPT_automasking_node_begin(
      data->ob, ss, ss->cache->automasking, &automask_data, data->nodes[n]);

  BKE_pbvh_vertex_iter_begin (ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE) {
    SCULPT_automasking_node_update(ss, &automask_data, &vd);

    if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) {
      MeshElemMap *vert_map = &ss->pmap->pmap[vd.index];
      for (int j = 0; j < ss->pmap->pmap[vd.index].count; j++) {
        const MPoly *p = &ss->mpoly[vert_map->indices[j]];

        float poly_center[3];
        BKE_mesh_calc_poly_center(p, &ss->mloop[p->loopstart], mvert, poly_center);

        if (!sculpt_brush_test_sq_fn(&test, poly_center)) {
          continue;
        }
        const float fade = bstrength * SCULPT_brush_strength_factor(ss,
                                                                    brush,
                                                                    vd.co,
                                                                    sqrtf(test.dist),
                                                                    vd.no,
                                                                    vd.fno,
                                                                    vd.mask ? *vd.mask : 0.0f,
                                                                    vd.vertex,
                                                                    thread_id,
                                                                    &automask_data);

        int new_fset = active_fset;

        if (use_fset_curve) {
          float no[3];
          SCULPT_vertex_normal_get(ss, vd.vertex, no);

          new_fset = new_fset_apply_curve(
              ss, data, new_fset, poly_center, no, &test, curve_ch, count);
        }

        if (fade > test_limit && ss->face_sets[vert_map->indices[j]] > 0) {
          bool ok = true;

          int fset = abs(ss->face_sets[vert_map->indices[j]]);

          // XXX kind of hackish, tries to sample faces that are within
          // 8 pixels of the center of the brush, and using a crude linear
          // scale at that - joeedh
          if (set_active_faceset &&
              fset != abs(ss->cache->automasking->settings.initial_face_set)) {

            float radius = ss->cache->radius;
            float pixels = 8;  // TODO: multiply with DPI
            radius = pixels * (radius / (float)ss->cache->dyntopo_pixel_radius);

            if (sqrtf(test.dist) < radius) {
              ss->cache->automasking->settings.initial_face_set = abs(fset);
              set_active_faceset = false;
              ss->cache->automasking->settings.flags |= BRUSH_AUTOMASKING_FACE_SETS;
            }
            else {
              ok = false;
            }
          }

          const MLoop *ml = &ss->mloop[p->loopstart];

          for (int i = 0; i < p->totloop; i++, ml++) {
            MVert *v = &ss->mvert[ml->v];
            float fno[3];

            MSculptVert *mv = ss->msculptverts + ml->v;

            MV_ADD_FLAG(mv, SCULPTVERT_NEED_BOUNDARY);

            copy_v3_v3(fno, ss->vert_normals[ml->v]);
            float mask = ss->vmask ? ss->vmask[ml->v] : 0.0f;

            const float fade2 = bstrength *
                                SCULPT_brush_strength_factor(ss,
                                                             brush,
                                                             v->co,
                                                             sqrtf(test.dist),
                                                             ss->vert_normals[ml->v],
                                                             fno,
                                                             mask,
                                                             BKE_pbvh_make_vref((intptr_t)ml->v),
                                                             thread_id,
                                                             &automask_data);

            if (fade2 < test_limit) {
              ok = false;
              break;
            }
          }

          if (ok) {
            ss->face_sets[vert_map->indices[j]] = new_fset;
            modified = true;
          }
        }
      }
    }
    else if (BKE_pbvh_type(ss->pbvh) == PBVH_BMESH) {
      BMVert *v = vd.bm_vert;
      BMIter iter;
      BMFace *f;

      BM_ITER_ELEM (f, &iter, v, BM_FACES_OF_VERT) {
        float poly_center[3];
        BM_face_calc_center_median(f, poly_center);

        if (sculpt_brush_test_sq_fn(&test, poly_center)) {
          const float fade = bstrength * SCULPT_brush_strength_factor(ss,
                                                                      brush,
                                                                      vd.co,
                                                                      sqrtf(test.dist),
                                                                      vd.no,
                                                                      vd.fno,
                                                                      vd.mask ? *vd.mask : 0.0f,
                                                                      vd.vertex,
                                                                      thread_id,
                                                                      &automask_data);

          int new_fset = active_fset;

          if (use_fset_curve) {
            float no[3];
            SCULPT_vertex_normal_get(ss, vd.vertex, no);

            new_fset = new_fset_apply_curve(
                ss, data, new_fset, poly_center, no, &test, curve_ch, count);
          }

          int fset = BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset);

          if ((!use_fset_strength || fade > test_limit) && fset > 0) {
            BMLoop *l = f->l_first;

            bool ok = true;

            // XXX kind of hackish, tries to sample faces that are within
            // 8 pixels of the center of the brush, and using a crude linear
            // scale at that - joeedh
            if (set_active_faceset &&
                abs(fset) != abs(ss->cache->automasking->settings.initial_face_set)) {

              float radius = ss->cache->radius;
              float pixels = 8;  // TODO: multiple with DPI
              radius = pixels * (radius / (float)ss->cache->dyntopo_pixel_radius);

              if (sqrtf(test.dist) < radius) {
                ss->cache->automasking->settings.initial_face_set = abs(fset);
                set_active_faceset = false;
                ss->cache->automasking->settings.flags |= BRUSH_AUTOMASKING_FACE_SETS;
              }
              else {
                ok = false;
              }
            }

            do {
              float mask = cd_mask >= 0 ? BM_ELEM_CD_GET_FLOAT(l->v, cd_mask) : 0.0f;

              const float fade2 = bstrength *
                                  SCULPT_brush_strength_factor(ss,
                                                               brush,
                                                               l->v->co,
                                                               sqrtf(test.dist),
                                                               l->v->no,
                                                               l->f->no,
                                                               mask,
                                                               BKE_pbvh_make_vref((intptr_t)l->v),
                                                               thread_id,
                                                               &automask_data);

              if (fade2 < test_limit) {
                ok = false;
                break;
              }

              MSculptVert *mv = BKE_PBVH_SCULPTVERT(ss->cd_sculpt_vert, l->v);
              MV_ADD_FLAG(mv, SCULPTVERT_NEED_BOUNDARY);
            } while ((l = l->next) != f->l_first);

            if (ok) {
              BM_ELEM_CD_SET_INT(f, ss->cd_faceset_offset, new_fset);
              modified = true;
            }
          }
        }
      }
    }
    else if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) {
      if (!sculpt_brush_test_sq_fn(&test, vd.co)) {
        continue;
      }
      const float fade = bstrength * SCULPT_brush_strength_factor(ss,
                                                                  brush,
                                                                  vd.co,
                                                                  sqrtf(test.dist),
                                                                  vd.no,
                                                                  vd.fno,
                                                                  vd.mask ? *vd.mask : 0.0f,
                                                                  vd.vertex,
                                                                  thread_id,
                                                                  &automask_data);
      int new_fset = active_fset;

      if (use_fset_curve) {
        float no[3];
        SCULPT_vertex_normal_get(ss, vd.vertex, no);

        new_fset = new_fset_apply_curve(
            ss, data, new_fset, ss->cache->location, no, &test, curve_ch, count);
      }

      if (!use_fset_strength || fade > test_limit) {
        SCULPT_vertex_face_set_set(ss, vd.vertex, new_fset);
        modified = true;
      }
    }
  }
  BKE_pbvh_vertex_iter_end;

  if (modified) {
    BKE_pbvh_node_mark_update_index_buffer(ss->pbvh, data->nodes[n]);
  }

  // restore automasking flag
  if (set_active_faceset) {
    ss->cache->automasking->settings.flags |= automasking_fset_flag;
  }
}

static void do_relax_face_sets_brush_task_cb_ex(void *__restrict userdata,
                                                const int n,
                                                const TaskParallelTLS *__restrict tls)
{
  SculptFaceSetDrawData *data = (SculptFaceSetDrawData *)userdata;
  SculptSession *ss = data->ob->sculpt;
  const Brush *brush = data->brush;
  float bstrength = ss->cache->bstrength;

  PBVHVertexIter vd;

  SculptBrushTest test;
  SculptBrushTestFn sculpt_brush_test_sq_fn = SCULPT_brush_test_init(
      ss, &test, (eBrushFalloffShape)data->brush->falloff_shape);

  const bool relax_face_sets = !(ss->cache->iteration_count % 3 == 0);
  /* This operations needs a strength tweak as the relax deformation is too weak by default. */
  if (relax_face_sets) {
    bstrength *= 2.0f;
  }

  const int thread_id = BLI_task_parallel_thread_id(tls);
  AutomaskingNodeData automask_data;
  SCULPT_automasking_node_begin(
      data->ob, ss, ss->cache->automasking, &automask_data, data->nodes[n]);

  bool do_reproject = SCULPT_need_reproject(ss);

  BKE_pbvh_vertex_iter_begin (ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE) {
    SCULPT_automasking_node_update(ss, &automask_data, &vd);

    if (!sculpt_brush_test_sq_fn(&test, vd.co)) {
      continue;
    }
    if (relax_face_sets == SCULPT_vertex_has_unique_face_set(ss, vd.vertex)) {
      continue;
    }

    float fade = bstrength * SCULPT_brush_strength_factor(ss,
                                                          brush,
                                                          vd.co,
                                                          sqrtf(test.dist),
                                                          vd.no,
                                                          vd.fno,
                                                          vd.mask ? *vd.mask : 0.0f,
                                                          vd.vertex,
                                                          thread_id,
                                                          &automask_data);

    CLAMP(fade, 0.0f, 1.0f);

    float oldco[3], oldno[3];

    copy_v3_v3(oldco, vd.co);
    SCULPT_vertex_normal_get(ss, vd.vertex, oldno);

    SCULPT_relax_vertex(ss,
                        &vd,
                        fade * bstrength,
                        (SculptBoundaryType)(SCULPT_BOUNDARY_DEFAULT | SCULPT_BOUNDARY_FACE_SET),
                        vd.co);
    if (vd.mvert) {
      BKE_pbvh_vert_tag_update_normal(ss->pbvh, vd.vertex);
    }
    if (do_reproject) {
      SCULPT_reproject_cdata(ss, vd.vertex, oldco, oldno);
    }
  }
  BKE_pbvh_vertex_iter_end;
}

ATTR_NO_OPT void SCULPT_do_draw_face_sets_brush(Sculpt *sd,
                                                Object *ob,
                                                PBVHNode **nodes,
                                                int totnode)
{
  SculptSession *ss = ob->sculpt;
  Brush *brush = ss->cache->brush ? ss->cache->brush : BKE_paint_brush(&sd->paint);

  BKE_sculpt_face_sets_ensure(ob);
  if (ss->pbvh) {
    Mesh *mesh = BKE_mesh_from_object(ob);
    BKE_pbvh_face_sets_color_set(
        ss->pbvh, mesh->face_sets_color_seed, mesh->face_sets_color_default);
  }

  BKE_curvemapping_init(brush->curve);

  /* Threaded loop over nodes. */
  SculptFaceSetDrawData data;

  data.sd = sd;
  data.ob = ob;
  data.brush = brush;
  data.nodes = nodes;
  data.faceset = abs(ss->cache->paint_face_set);
  data.use_fset_curve = false;
  data.use_fset_strength = true;
  data.bstrength = ss->cache->bstrength;
  data.count = 1;

  bool threaded = true;

  /*for ctrl invert mode we have to set the automasking initial_face_set
    to the first non-current faceset that is found*/
  int automasking_flags = SCULPT_get_int(ss, automasking, sd, brush);

  if (SCULPT_stroke_is_first_brush_step(ss->cache)) {
    if (ss->cache->invert && ss->cache->automasking &&
        (automasking_flags & BRUSH_AUTOMASKING_FACE_SETS)) {
      ss->cache->automasking->settings.current_face_set =
          ss->cache->automasking->settings.initial_face_set;
    }
  }

  if (ss->cache->invert && !ss->cache->alt_smooth && ss->cache->automasking &&
      ss->cache->automasking->settings.initial_face_set ==
          ss->cache->automasking->settings.current_face_set) {
    threaded = false;
  }

  // ctrl-click is single threaded since the tasks will set the initial face set
  TaskParallelSettings settings;
  BKE_pbvh_parallel_range_settings(&settings, threaded, totnode);
  if (ss->cache->alt_smooth) {
    SCULPT_boundary_info_ensure(ob);
    for (int i = 0; i < 4; i++) {
      BLI_task_parallel_range(0, totnode, &data, do_relax_face_sets_brush_task_cb_ex, &settings);
    }
  }
  else {
    BLI_task_parallel_range(0, totnode, &data, do_draw_face_sets_brush_task_cb_ex, &settings);
  }
}

/* Face Sets Operators */

enum eSculptFaceGroupsCreateModes {
  SCULPT_FACE_SET_MASKED = 0,
  SCULPT_FACE_SET_VISIBLE = 1,
  SCULPT_FACE_SET_ALL = 2,
  SCULPT_FACE_SET_SELECTION = 3,
};

static EnumPropertyItem prop_sculpt_face_set_create_types[] = {
    {
        SCULPT_FACE_SET_MASKED,
        "MASKED",
        0,
        "Face Set from Masked",
        "Create a new Face Set from the masked faces",
    },
    {
        SCULPT_FACE_SET_VISIBLE,
        "VISIBLE",
        0,
        "Face Set from Visible",
        "Create a new Face Set from the visible vertices",
    },
    {
        SCULPT_FACE_SET_ALL,
        "ALL",
        0,
        "Face Set Full Mesh",
        "Create an unique Face Set with all faces in the sculpt",
    },
    {
        SCULPT_FACE_SET_SELECTION,
        "SELECTION",
        0,
        "Face Set from Edit Mode Selection",
        "Create an Face Set corresponding to the Edit Mode face selection",
    },
    {0, NULL, 0, NULL, NULL},
};

static int sculpt_face_set_create_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;
  Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);

  const int mode = RNA_enum_get(op->ptr, "mode");

  BKE_sculpt_update_object_for_edit(depsgraph, ob, true, mode == SCULPT_FACE_SET_MASKED, false);

  SCULPT_face_random_access_ensure(ss);
  SCULPT_vertex_random_access_ensure(ss);

  const int tot_vert = SCULPT_vertex_count_get(ss);
  float threshold = 0.5f;

  PBVH *pbvh = ob->sculpt->pbvh;
  PBVHNode **nodes;
  int totnode;
  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);

  if (!nodes) {
    return OPERATOR_CANCELLED;
  }

  SCULPT_undo_push_begin(ob, op);
  SCULPT_undo_push_node(ob, nodes[0], SCULPT_UNDO_FACE_SETS);

  const int next_face_set = SCULPT_face_set_next_available_get(ss);

  if (mode == SCULPT_FACE_SET_MASKED) {
    for (int i = 0; i < tot_vert; i++) {
      PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

      if (SCULPT_vertex_mask_get(ss, vertex) >= threshold &&
          SCULPT_vertex_visible_get(ss, vertex)) {
        SCULPT_vertex_face_set_set(ss, vertex, next_face_set);
      }
    }
  }

  if (mode == SCULPT_FACE_SET_VISIBLE) {

    /* If all vertices in the sculpt are visible, create the new face set and update the default
     * color. This way the new face set will be white, which is a quick way of disabling all face
     * sets and the performance hit of rendering the overlay. */
    bool all_visible = true;
    for (int i = 0; i < tot_vert; i++) {
      PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

      if (!SCULPT_vertex_visible_get(ss, vertex)) {
        all_visible = false;
        break;
      }
    }

    if (all_visible) {
      Mesh *mesh = (Mesh *)ob->data;
      mesh->face_sets_color_default = next_face_set;
      BKE_pbvh_face_sets_color_set(
          ss->pbvh, mesh->face_sets_color_seed, mesh->face_sets_color_default);
    }

    for (int i = 0; i < tot_vert; i++) {
      PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

      if (SCULPT_vertex_visible_get(ss, vertex)) {
        SCULPT_vertex_face_set_set(ss, vertex, next_face_set);
      }
    }
  }

  if (mode == SCULPT_FACE_SET_ALL) {
    for (int i = 0; i < tot_vert; i++) {
      PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

      SCULPT_vertex_face_set_set(ss, vertex, next_face_set);
    }
  }

  if (mode == SCULPT_FACE_SET_SELECTION) {
    const int totface = ss->totfaces;

    for (int i = 0; i < totface; i++) {
      PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, i);

      // XXX check hidden?
      bool ok;
      if (ss->attrs.hide_poly) {
        ok = *(bool *)BKE_sculpt_face_attr_get(fref, ss->attrs.hide_poly);
      }

      ok = ok && SCULPT_face_select_get(ss, fref);

      if (ok) {
        SCULPT_face_set_set(ss, fref, next_face_set);
      }
    }
  }

  for (int i = 0; i < totnode; i++) {
    BKE_pbvh_node_mark_redraw(nodes[i]);
  }

  MEM_SAFE_FREE(nodes);

  SCULPT_undo_push_end(ob);

  SCULPT_tag_update_overlays(C);

  return OPERATOR_FINISHED;
}

void SCULPT_OT_face_sets_create(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Create Face Set";
  ot->idname = "SCULPT_OT_face_sets_create";
  ot->description = "Create a new Face Set";

  /* api callbacks */
  ot->exec = sculpt_face_set_create_exec;
  ot->poll = SCULPT_mode_poll;

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(
      ot->srna, "mode", prop_sculpt_face_set_create_types, SCULPT_FACE_SET_MASKED, "Mode", "");
}

enum eSculptFaceSetsInitMode {
  SCULPT_FACE_SETS_FROM_LOOSE_PARTS = 0,
  SCULPT_FACE_SETS_FROM_MATERIALS = 1,
  SCULPT_FACE_SETS_FROM_NORMALS = 2,
  SCULPT_FACE_SETS_FROM_UV_SEAMS = 3,
  SCULPT_FACE_SETS_FROM_CREASES = 4,
  SCULPT_FACE_SETS_FROM_SHARP_EDGES = 5,
  SCULPT_FACE_SETS_FROM_BEVEL_WEIGHT = 6,
  SCULPT_FACE_SETS_FROM_FACE_MAPS = 7,
  SCULPT_FACE_SETS_FROM_FACE_SET_BOUNDARIES = 8,
};

static EnumPropertyItem prop_sculpt_face_sets_init_types[] = {
    {
        SCULPT_FACE_SETS_FROM_LOOSE_PARTS,
        "LOOSE_PARTS",
        0,
        "Face Sets from Loose Parts",
        "Create a Face Set per loose part in the mesh",
    },
    {
        SCULPT_FACE_SETS_FROM_MATERIALS,
        "MATERIALS",
        0,
        "Face Sets from Material Slots",
        "Create a Face Set per Material Slot",
    },
    {
        SCULPT_FACE_SETS_FROM_NORMALS,
        "NORMALS",
        0,
        "Face Sets from Mesh Normals",
        "Create Face Sets for Faces that have similar normal",
    },
    {
        SCULPT_FACE_SETS_FROM_UV_SEAMS,
        "UV_SEAMS",
        0,
        "Face Sets from UV Seams",
        "Create Face Sets using UV Seams as boundaries",
    },
    {
        SCULPT_FACE_SETS_FROM_CREASES,
        "CREASES",
        0,
        "Face Sets from Edge Creases",
        "Create Face Sets using Edge Creases as boundaries",
    },
    {
        SCULPT_FACE_SETS_FROM_BEVEL_WEIGHT,
        "BEVEL_WEIGHT",
        0,
        "Face Sets from Bevel Weight",
        "Create Face Sets using Bevel Weights as boundaries",
    },
    {
        SCULPT_FACE_SETS_FROM_SHARP_EDGES,
        "SHARP_EDGES",
        0,
        "Face Sets from Sharp Edges",
        "Create Face Sets using Sharp Edges as boundaries",
    },
    {
        SCULPT_FACE_SETS_FROM_FACE_MAPS,
        "FACE_MAPS",
        0,
        "Face Sets from Face Maps",
        "Create a Face Set per Face Map",
    },
    {
        SCULPT_FACE_SETS_FROM_FACE_SET_BOUNDARIES,
        "FACE_SET_BOUNDARIES",
        0,
        "Face Sets from Face Set Boundaries",
        "Create a Face Set per isolated Face Set",
    },
    {0, NULL, 0, NULL, NULL},
};

typedef bool (*face_sets_flood_fill_test)(
    BMesh *bm, BMFace *from_f, BMEdge *from_e, BMFace *to_f, const float threshold);

static bool sculpt_face_sets_init_loose_parts_test(BMesh *UNUSED(bm),
                                                   BMFace *UNUSED(from_f),
                                                   BMEdge *UNUSED(from_e),
                                                   BMFace *UNUSED(to_f),
                                                   const float UNUSED(threshold))
{
  return true;
}

static bool sculpt_face_sets_init_normals_test(
    BMesh *UNUSED(bm), BMFace *from_f, BMEdge *UNUSED(from_e), BMFace *to_f, const float threshold)
{
  return fabsf(dot_v3v3(from_f->no, to_f->no)) > threshold;
}

static bool sculpt_face_sets_init_uv_seams_test(BMesh *UNUSED(bm),
                                                BMFace *UNUSED(from_f),
                                                BMEdge *from_e,
                                                BMFace *UNUSED(to_f),
                                                const float UNUSED(threshold))
{
  return !BM_elem_flag_test(from_e, BM_ELEM_SEAM);
}

static bool sculpt_face_sets_init_crease_test(
    BMesh *bm, BMFace *UNUSED(from_f), BMEdge *from_e, BMFace *UNUSED(to_f), const float threshold)
{
  return BM_elem_float_data_get(&bm->edata, from_e, CD_CREASE) < threshold;
}

static bool sculpt_face_sets_init_bevel_weight_test(
    BMesh *bm, BMFace *UNUSED(from_f), BMEdge *from_e, BMFace *UNUSED(to_f), const float threshold)
{
  return BM_elem_float_data_get(&bm->edata, from_e, CD_BWEIGHT) < threshold;
}

static bool sculpt_face_sets_init_sharp_edges_test(BMesh *UNUSED(bm),
                                                   BMFace *UNUSED(from_f),
                                                   BMEdge *from_e,
                                                   BMFace *UNUSED(to_f),
                                                   const float UNUSED(threshold))
{
  return BM_elem_flag_test(from_e, BM_ELEM_SMOOTH);
}

static bool sculpt_face_sets_init_face_set_boundary_test(
    BMesh *bm, BMFace *from_f, BMEdge *UNUSED(from_e), BMFace *to_f, const float UNUSED(threshold))
{
  const int cd_face_sets_offset = CustomData_get_offset_named(
      &bm->pdata, CD_PROP_INT32, ".sculpt_face_sets");

  return BM_ELEM_CD_GET_INT(from_f, cd_face_sets_offset) ==
         BM_ELEM_CD_GET_INT(to_f, cd_face_sets_offset);
}

static void sculpt_face_sets_init_flood_fill(Object *ob,
                                             face_sets_flood_fill_test test,
                                             const float threshold)
{
  SculptSession *ss = ob->sculpt;
  Mesh *mesh = (Mesh *)ob->data;
  BMesh *bm;

  SCULPT_vertex_random_access_ensure(ss);
  SCULPT_face_random_access_ensure(ss);

  bm = sculpt_faceset_bm_begin(ob, ss, mesh);

  BLI_bitmap *visited_faces = BLI_BITMAP_NEW(ss->totfaces, "visited faces");
  const int totfaces = ss->totfaces;  // mesh->totpoly;

  if (!ss->bm) {
    BM_mesh_elem_index_ensure(bm, BM_FACE);
    BM_mesh_elem_table_ensure(bm, BM_FACE);
  }

  int next_face_set = 1;

  for (int i = 0; i < totfaces; i++) {
    if (BLI_BITMAP_TEST(visited_faces, i)) {
      continue;
    }
    GSQueue *queue;
    queue = BLI_gsqueue_new(sizeof(int));

    PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, i);
    SCULPT_face_set_set(ss, fref, next_face_set);

    BLI_BITMAP_ENABLE(visited_faces, i);
    BLI_gsqueue_push(queue, &i);

    while (!BLI_gsqueue_is_empty(queue)) {
      int from_f;
      BLI_gsqueue_pop(queue, &from_f);

      BMFace *f, *f_neighbor;
      BMEdge *ed;
      BMIter iter_a, iter_b;

      f = BM_face_at_index(bm, from_f);

      BM_ITER_ELEM (ed, &iter_a, f, BM_EDGES_OF_FACE) {
        BM_ITER_ELEM (f_neighbor, &iter_b, ed, BM_FACES_OF_EDGE) {
          if (f_neighbor == f) {
            continue;
          }
          int neighbor_face_index = BM_elem_index_get(f_neighbor);
          if (BLI_BITMAP_TEST(visited_faces, neighbor_face_index)) {
            continue;
          }
          if (!test(bm, f, ed, f_neighbor, threshold)) {
            continue;
          }

          PBVHFaceRef fref2 = BKE_pbvh_index_to_face(ss->pbvh, neighbor_face_index);
          SCULPT_face_set_set(ss, fref2, next_face_set);

          BLI_BITMAP_ENABLE(visited_faces, neighbor_face_index);
          BLI_gsqueue_push(queue, &neighbor_face_index);
        }
      }
    }

    next_face_set += 1;

    BLI_gsqueue_free(queue);
  }

  MEM_SAFE_FREE(visited_faces);

  sculpt_faceset_bm_end(ss, bm);
}

static void sculpt_face_sets_init_loop(Object *ob, const int mode)
{
  SculptSession *ss = ob->sculpt;

  SCULPT_face_random_access_ensure(ss);

  int cd_fmaps_offset = -1;
  if (ss->bm) {
    cd_fmaps_offset = CustomData_get_offset(&ss->bm->pdata, CD_FACEMAP);
  }

  Mesh *me = NULL;
  int *fmaps = NULL;

  if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) {
    me = (Mesh *)ob->data;
    fmaps = (int *)CustomData_get_layer(&me->pdata, CD_FACEMAP);
  }
  else if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) {
    fmaps = (int *)CustomData_get_layer(ss->pdata, CD_FACEMAP);
  }

  for (int i = 0; i < ss->totfaces; i++) {
    PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, i);

    if (mode == SCULPT_FACE_SETS_FROM_MATERIALS) {
      SCULPT_face_set_set(ss, fref, (int)(sculpt_face_material_get(ss, fref) + 1));
    }
    else if (mode == SCULPT_FACE_SETS_FROM_FACE_MAPS) {
      int fmap = 1;

      switch (BKE_pbvh_type(ss->pbvh)) {
        case PBVH_BMESH: {
          BMFace *f = (BMFace *)fref.i;

          if (cd_fmaps_offset >= 0) {
            fmap = BM_ELEM_CD_GET_INT(f, cd_fmaps_offset) + 2;
          }

          break;
        }
        case PBVH_FACES:
        case PBVH_GRIDS: {
          if (fmaps) {
            fmap = fmaps[i] + 2;
          }
          break;
        }
      }

      SCULPT_face_set_set(ss, fref, fmap);
    }
  }
}

static int sculpt_face_set_init_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;
  Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);

  const int mode = RNA_enum_get(op->ptr, "mode");

  BKE_sculpt_update_object_for_edit(depsgraph, ob, true, false, false);
  BKE_sculpt_face_sets_ensure(ob);

  /* Dyntopo not supported. */
  if (BKE_pbvh_type(ss->pbvh) == PBVH_BMESH) {
    return OPERATOR_CANCELLED;
  }

  PBVH *pbvh = ob->sculpt->pbvh;
  PBVHNode **nodes;
  int totnode;
  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);

  if (!nodes) {
    return OPERATOR_CANCELLED;
  }

  SCULPT_undo_push_begin(ob, op);
  SCULPT_undo_push_node(ob, nodes[0], SCULPT_UNDO_FACE_SETS);

  const float threshold = RNA_float_get(op->ptr, "threshold");

  switch (mode) {
    case SCULPT_FACE_SETS_FROM_LOOSE_PARTS:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_loose_parts_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_MATERIALS:
      sculpt_face_sets_init_loop(ob, SCULPT_FACE_SETS_FROM_MATERIALS);
      break;
    case SCULPT_FACE_SETS_FROM_NORMALS:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_normals_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_UV_SEAMS:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_uv_seams_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_CREASES:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_crease_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_SHARP_EDGES:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_sharp_edges_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_BEVEL_WEIGHT:
      sculpt_face_sets_init_flood_fill(ob, sculpt_face_sets_init_bevel_weight_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_FACE_SET_BOUNDARIES:
      sculpt_face_sets_init_flood_fill(
          ob, sculpt_face_sets_init_face_set_boundary_test, threshold);
      break;
    case SCULPT_FACE_SETS_FROM_FACE_MAPS:
      sculpt_face_sets_init_loop(ob, SCULPT_FACE_SETS_FROM_FACE_MAPS);
      break;
  }

  SCULPT_undo_push_end(ob);

  for (int i = 0; i < totnode; i++) {
    BKE_pbvh_node_mark_redraw(nodes[i]);
  }

  BKE_pbvh_update_vertex_data(ss->pbvh, PBVH_UpdateVisibility);

  MEM_SAFE_FREE(nodes);

  if (BKE_pbvh_type(pbvh) == PBVH_FACES) {
    BKE_mesh_flush_hidden_from_verts((Mesh *)ob->data);
  }

  SCULPT_tag_update_overlays(C);

  return OPERATOR_FINISHED;
}

void SCULPT_OT_face_sets_init(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Init Face Sets";
  ot->idname = "SCULPT_OT_face_sets_init";
  ot->description = "Initializes all Face Sets in the mesh";

  /* api callbacks */
  ot->exec = sculpt_face_set_init_exec;
  ot->poll = SCULPT_mode_poll;

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(
      ot->srna, "mode", prop_sculpt_face_sets_init_types, SCULPT_FACE_SET_MASKED, "Mode", "");
  RNA_def_float(
      ot->srna,
      "threshold",
      0.5f,
      0.0f,
      1.0f,
      "Threshold",
      "Minimum value to consider a certain attribute a boundary when creating the Face Sets",
      0.0f,
      1.0f);
}

enum eSculptFaceGroupVisibilityModes {
  SCULPT_FACE_SET_VISIBILITY_TOGGLE = 0,
  SCULPT_FACE_SET_VISIBILITY_SHOW_ACTIVE = 1,
  SCULPT_FACE_SET_VISIBILITY_HIDE_ACTIVE = 2,
  SCULPT_FACE_SET_VISIBILITY_INVERT = 3,
};

static EnumPropertyItem prop_sculpt_face_sets_change_visibility_types[] = {
    {
        SCULPT_FACE_SET_VISIBILITY_TOGGLE,
        "TOGGLE",
        0,
        "Toggle Visibility",
        "Hide all Face Sets except for the active one",
    },
    {
        SCULPT_FACE_SET_VISIBILITY_SHOW_ACTIVE,
        "SHOW_ACTIVE",
        0,
        "Show Active Face Set",
        "Show Active Face Set",
    },
    {
        SCULPT_FACE_SET_VISIBILITY_HIDE_ACTIVE,
        "HIDE_ACTIVE",
        0,
        "Hide Active Face Sets",
        "Hide Active Face Sets",
    },
    {
        SCULPT_FACE_SET_VISIBILITY_INVERT,
        "INVERT",
        0,
        "Invert Face Set Visibility",
        "Invert Face Set Visibility",
    },
    {0, nullptr, 0, nullptr, nullptr},
};

void SCULPT_face_sets_visibility_all_set(SculptSession *ss, bool state)
{
  for (int i = 0; i < ss->totfaces; i++) {
    PBVHFaceRef face = BKE_pbvh_index_to_face(ss->pbvh, i);

    *(bool *)BKE_sculpt_face_attr_get(face, ss->attrs.hide_poly) = !state;
  }
}

void SCULPT_face_sets_visibility_invert(SculptSession *ss)
{
  for (int i = 0; i < ss->totfaces; i++) {
    PBVHFaceRef face = BKE_pbvh_index_to_face(ss->pbvh, i);

    *(bool *)BKE_sculpt_face_attr_get(face, ss->attrs.hide_poly) ^= true;
  }
}

static int sculpt_face_sets_change_visibility_exec(bContext *C, wmOperator *op)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;
  Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);

  Mesh *mesh = BKE_object_get_original_mesh(ob);

  BKE_sculpt_update_object_for_edit(depsgraph, ob, true, true, false);
  BKE_sculpt_face_sets_ensure(ob);

  const int cd_hide_poly = ss->attrs.hide_poly ? ss->attrs.hide_poly->bmesh_cd_offset : -1;
  const int mode = RNA_enum_get(op->ptr, "mode");
  const int tot_vert = SCULPT_vertex_count_get(ss);
  const int active_face_set = SCULPT_active_face_set_get(ss);

  SCULPT_undo_push_begin(ob, op);

  PBVH *pbvh = ob->sculpt->pbvh;
  PBVHNode **nodes;
  int totnode;

  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);

  if (totnode == 0) {
    MEM_SAFE_FREE(nodes);
    return OPERATOR_CANCELLED;
  }

  SCULPT_undo_push_node(ob, nodes[0], SCULPT_UNDO_FACE_SETS);

  if (mode == SCULPT_FACE_SET_VISIBILITY_TOGGLE) {
    bool hidden_vertex = false;

    /* This can fail with regular meshes with non-manifold geometry as the visibility state can't
     * be synced from face sets to non-manifold vertices. */
    if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) {
      for (int i = 0; i < tot_vert; i++) {
        PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

        if (!SCULPT_vertex_visible_get(ss, vertex)) {
          hidden_vertex = true;
          break;
        }
      }
    }
    else if (ss->bm) {
      BMIter iter;
      BMFace *f;

      BM_ITER_MESH (f, &iter, ss->bm, BM_FACES_OF_MESH) {
        if (cd_hide_poly != -1 && BM_ELEM_CD_GET_BOOL(f, cd_hide_poly)) {
          hidden_vertex = true;
          break;
        }
      }
    }
    else {
      for (int i = 0; i < ss->totfaces; i++) {
        if (ss->hide_poly && ss->hide_poly[i]) {
          hidden_vertex = true;
          break;
        }
      }
    }

    SCULPT_face_sets_visibility_all_set(ss, hidden_vertex);

    if (!hidden_vertex) {
      SCULPT_face_set_visibility_set(ss, active_face_set, true);
    }
  }

  if (mode == SCULPT_FACE_SET_VISIBILITY_SHOW_ACTIVE) {
    SCULPT_face_sets_visibility_all_set(ss, false);
    SCULPT_face_set_visibility_set(ss, active_face_set, true);
  }

  if (mode == SCULPT_FACE_SET_VISIBILITY_HIDE_ACTIVE) {
    SCULPT_face_set_visibility_set(ss, active_face_set, false);
  }

  if (mode == SCULPT_FACE_SET_VISIBILITY_INVERT) {
    SCULPT_face_sets_visibility_invert(ss);
  }

  /* For modes that use the cursor active vertex, update the rotation origin for viewport
   * navigation. */
  if (ELEM(mode, SCULPT_FACE_SET_VISIBILITY_TOGGLE, SCULPT_FACE_SET_VISIBILITY_SHOW_ACTIVE)) {
    UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
    float location[3];
    copy_v3_v3(location, SCULPT_active_vertex_co_get(ss));
    mul_m4_v3(ob->obmat, location);
    copy_v3_v3(ups->average_stroke_accum, location);
    ups->average_stroke_counter = 1;
    ups->last_stroke_valid = true;
  }

  SCULPT_undo_push_end(ob);

  BKE_pbvh_update_vertex_data(ss->pbvh, PBVH_UpdateVisibility);

  MEM_SAFE_FREE(nodes);

  SCULPT_tag_update_overlays(C);

  return OPERATOR_FINISHED;
}

static int sculpt_face_sets_change_visibility_invoke(bContext *C,
                                                     wmOperator *op,
                                                     const wmEvent *event)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;

  /* Update the active vertex and Face Set using the cursor position to avoid relying on the
   * paint cursor updates. */
  SculptCursorGeometryInfo sgi;
  const float mval_fl[2] = {float(event->mval[0]), float(event->mval[1])};
  SCULPT_vertex_random_access_ensure(ss);
  SCULPT_cursor_geometry_info_update(C, &sgi, mval_fl, false, false);

  return sculpt_face_sets_change_visibility_exec(C, op);
}

void SCULPT_OT_face_sets_change_visibility(wmOperatorType *ot)
{
  /* Identifiers. */
  ot->name = "Face Sets Visibility";
  ot->idname = "SCULPT_OT_face_set_change_visibility";
  ot->description = "Change the visibility of the Face Sets of the sculpt";

  /* Api callbacks. */
  ot->exec = sculpt_face_sets_change_visibility_exec;
  ot->invoke = sculpt_face_sets_change_visibility_invoke;
  ot->poll = SCULPT_mode_poll;

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(ot->srna,
               "mode",
               prop_sculpt_face_sets_change_visibility_types,
               SCULPT_FACE_SET_VISIBILITY_TOGGLE,
               "Mode",
               "");
}

static int sculpt_face_sets_randomize_colors_exec(bContext *C, wmOperator * /*op*/)
{

  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;

  PBVH *pbvh = ob->sculpt->pbvh;
  PBVHNode **nodes;
  int totnode;
  Mesh *mesh = (Mesh *)ob->data;

  SCULPT_face_random_access_ensure(ss);

  mesh->face_sets_color_seed += 1;
  if (ss->face_sets || (ss->bm && ss->cd_faceset_offset >= 0)) {
    const int random_index = clamp_i(ss->totfaces * BLI_hash_int_01(mesh->face_sets_color_seed),
                                     0,
                                     max_ii(0, ss->totfaces - 1));

    PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, random_index);
    mesh->face_sets_color_default = SCULPT_face_set_get(ss, fref);
  }
  BKE_pbvh_face_sets_color_set(pbvh, mesh->face_sets_color_seed, mesh->face_sets_color_default);

  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);
  for (int i = 0; i < totnode; i++) {
    BKE_pbvh_node_mark_redraw(nodes[i]);
  }

  MEM_SAFE_FREE(nodes);

  SCULPT_tag_update_overlays(C);

  return OPERATOR_FINISHED;
}

void SCULPT_OT_face_sets_randomize_colors(wmOperatorType *ot)
{
  /* Identifiers. */
  ot->name = "Randomize Face Sets Colors";
  ot->idname = "SCULPT_OT_face_sets_randomize_colors";
  ot->description = "Generates a new set of random colors to render the Face Sets in the viewport";

  /* Api callbacks. */
  ot->exec = sculpt_face_sets_randomize_colors_exec;
  ot->poll = SCULPT_mode_poll;

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

enum eSculptFaceSetEditMode {
  SCULPT_FACE_SET_EDIT_GROW = 0,
  SCULPT_FACE_SET_EDIT_SHRINK = 1,
  SCULPT_FACE_SET_EDIT_DELETE_GEOMETRY = 2,
  SCULPT_FACE_SET_EDIT_FAIR_POSITIONS = 3,
  SCULPT_FACE_SET_EDIT_FAIR_TANGENCY = 4,
  SCULPT_FACE_SET_EDIT_FAIR_CURVATURE = 5,
  SCULPT_FACE_SET_EDIT_FILL_COMPONENT = 6,
  SCULPT_FACE_SET_EDIT_EXTRUDE = 7,
  SCULPT_FACE_SET_EDIT_FAIR_ALL_TANGENCY = 8,
};

static EnumPropertyItem prop_sculpt_face_sets_edit_types[] = {
    {
        SCULPT_FACE_SET_EDIT_GROW,
        "GROW",
        0,
        "Grow Face Set",
        "Grows the Face Sets boundary by one face based on mesh topology",
    },
    {
        SCULPT_FACE_SET_EDIT_SHRINK,
        "SHRINK",
        0,
        "Shrink Face Set",
        "Shrinks the Face Sets boundary by one face based on mesh topology",
    },
    {
        SCULPT_FACE_SET_EDIT_DELETE_GEOMETRY,
        "DELETE_GEOMETRY",
        0,
        "Delete Geometry",
        "Deletes the faces that are assigned to the Face Set",
    },
    {
        SCULPT_FACE_SET_EDIT_FAIR_POSITIONS,
        "FAIR_POSITIONS",
        0,
        "Fair Positions",
        "Creates a smooth as possible geometry patch from the Face Set minimizing changes in "
        "vertex positions",
    },
    {
        SCULPT_FACE_SET_EDIT_FAIR_TANGENCY,
        "FAIR_TANGENCY",
        0,
        "Fair Tangency",
        "Creates a smooth as possible geometry patch from the Face Set minimizing changes in "
        "vertex tangents",
    },
    /*
    {
        SCULPT_FACE_SET_EDIT_FAIR_CURVATURE,
        "FAIR_CURVATURE",
        0,
        "Fair Curvature",
        "Creates a smooth as possible geometry patch from the Face Set minimizing changes in "
        "surface curvature",
    },
    */
    {
        SCULPT_FACE_SET_EDIT_FILL_COMPONENT,
        "FILL_COMPONENT",
        0,
        "Fill Component",
        "Expand a Face Set to fill all affected connected components",
    },
    {
        SCULPT_FACE_SET_EDIT_EXTRUDE,
        "EXTRUDE",
        0,
        "Extrude",
        "Extrude a Face Set along the normals of the faces",
    },
    {
        SCULPT_FACE_SET_EDIT_FAIR_ALL_TANGENCY,
        "ALL_TANGENCY",
        0,
        "All tangency",
        "Extrude a Face Set along the normals of the faces",
    },
    {0, NULL, 0, NULL, NULL},
};

static void sculpt_face_set_grow_bmesh(Object *ob,
                                       SculptSession *ss,
                                       const int *prev_face_sets,
                                       const int active_face_set_id,
                                       const bool modify_hidden)
{
  BMesh *bm = ss->bm;
  BMIter iter;
  BMFace *f;
  Vector<BMFace *> faces;

  if (ss->cd_faceset_offset < 0) {
    return;
  }

  BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
    if (BM_elem_flag_test(f, BM_ELEM_HIDDEN) && !modify_hidden) {
      continue;
    }

    int fset = abs(BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset));

    if (fset == active_face_set_id) {
      faces.append(f);
    }
  }

  for (BMFace *f : faces) {
    BMLoop *l = f->l_first;

    do {
      if (l->radial_next != l) {
        BM_ELEM_CD_SET_INT(l->radial_next->f, ss->cd_faceset_offset, active_face_set_id);
      }
      l = l->next;
    } while (l != f->l_first);
  }
}

static void sculpt_face_set_grow(Object *ob,
                                 SculptSession *ss,
                                 const int *prev_face_sets,
                                 const int active_face_set_id,
                                 const bool modify_hidden)
{
  if (ss && ss->bm) {
    sculpt_face_set_grow_bmesh(ob, ss, prev_face_sets, active_face_set_id, modify_hidden);
    return;
  }

  Mesh *mesh = BKE_mesh_from_object(ob);
  for (int p = 0; p < mesh->totpoly; p++) {
    if (!modify_hidden && prev_face_sets[p] <= 0) {
      continue;
    }
    const MPoly *c_poly = &mesh->mpoly[p];
    for (int l = 0; l < c_poly->totloop; l++) {
      const MLoop *c_loop = &mesh->mloop[c_poly->loopstart + l];
      const MeshElemMap *vert_map = &ss->pmap->pmap[c_loop->v];
      for (int i = 0; i < vert_map->count; i++) {
        const int neighbor_face_index = vert_map->indices[i];
        if (neighbor_face_index == p) {
          continue;
        }
        if (abs(prev_face_sets[neighbor_face_index]) == active_face_set_id) {
          ss->face_sets[p] = active_face_set_id;
        }
      }
    }
  }
}

static void sculpt_face_set_fill_component(Object *ob,
                                           SculptSession *ss,
                                           const int active_face_set_id,
                                           const bool UNUSED(modify_hidden))
{
  SCULPT_connected_components_ensure(ob);
  GSet *connected_components = BLI_gset_int_new("affected_components");

  const int totvert = SCULPT_vertex_count_get(ss);
  for (int i = 0; i < totvert; i++) {
    PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

    if (!SCULPT_vertex_has_face_set(ss, vertex, active_face_set_id)) {
      continue;
    }
    const int vertex_connected_component = ss->vertex_info.connected_component[i];
    if (BLI_gset_haskey(connected_components, POINTER_FROM_INT(vertex_connected_component))) {
      continue;
    }
    BLI_gset_add(connected_components, POINTER_FROM_INT(vertex_connected_component));
  }

  for (int i = 0; i < totvert; i++) {
    PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, i);

    const int vertex_connected_component = ss->vertex_info.connected_component[i];
    if (!BLI_gset_haskey(connected_components, POINTER_FROM_INT(vertex_connected_component))) {
      continue;
    }

    SCULPT_vertex_face_set_set(ss, vertex, active_face_set_id);
  }

  BLI_gset_free(connected_components, NULL);
}

static void sculpt_face_set_shrink_bmesh(Object *ob,
                                         SculptSession *ss,
                                         const int *prev_face_sets,
                                         const int active_face_set_id,
                                         const bool modify_hidden)
{
  BMesh *bm = ss->bm;
  BMIter iter;
  BMFace *f;
  Vector<BMFace *> faces;

  if (ss->cd_faceset_offset < 0) {
    return;
  }

  BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
    if (BM_elem_flag_test(f, BM_ELEM_HIDDEN) && !modify_hidden) {
      continue;
    }

    int fset = abs(BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset));

    if (fset == active_face_set_id) {
      faces.append(f);
    }
  }

  for (BMFace *f : faces) {
    BMLoop *l = f->l_first;

    do {
      if (!modify_hidden && BM_elem_flag_test(l->radial_next->f, BM_ELEM_HIDDEN)) {
        l = l->next;
        continue;
      }

      if (l->radial_next != l &&
          abs(BM_ELEM_CD_GET_INT(l->radial_next->f, ss->cd_faceset_offset)) !=
              abs(active_face_set_id)) {
        BM_ELEM_CD_SET_INT(f,
                           ss->cd_faceset_offset,
                           BM_ELEM_CD_GET_INT(l->radial_next->f, ss->cd_faceset_offset));
        break;
      }
      l = l->next;
    } while (l != f->l_first);
  }
}

static void sculpt_face_set_shrink(Object *ob,
                                   SculptSession *ss,
                                   const int *prev_face_sets,
                                   const int active_face_set_id,
                                   const bool modify_hidden)
{
  if (ss && ss->bm) {
    sculpt_face_set_shrink_bmesh(ob, ss, prev_face_sets, active_face_set_id, modify_hidden);
    return;
  }

  Mesh *mesh = BKE_mesh_from_object(ob);
  for (int p = 0; p < mesh->totpoly; p++) {
    if (!modify_hidden && prev_face_sets[p] <= 0) {
      continue;
    }
    if (abs(prev_face_sets[p]) == active_face_set_id) {
      const MPoly *c_poly = &mesh->mpoly[p];
      for (int l = 0; l < c_poly->totloop; l++) {
        const MLoop *c_loop = &mesh->mloop[c_poly->loopstart + l];
        const MeshElemMap *vert_map = &ss->pmap->pmap[c_loop->v];
        for (int i = 0; i < vert_map->count; i++) {
          const int neighbor_face_index = vert_map->indices[i];
          if (neighbor_face_index == p) {
            continue;
          }
          if (abs(prev_face_sets[neighbor_face_index]) != active_face_set_id) {
            ss->face_sets[p] = prev_face_sets[neighbor_face_index];
          }
        }
      }
    }
  }
}

static bool check_single_face_set(SculptSession *ss, const bool check_visible_only)
{
  if (!ss->totfaces) {
    return true;
  }

  int first_face_set = SCULPT_FACE_SET_NONE;

  if (check_visible_only) {
    for (int f = 0; f < ss->totfaces; f++) {
      PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, f);
      int fset = SCULPT_face_set_get(ss, fref);

      if (fset > 0) {
        first_face_set = fset;
        break;
      }
    }
  }
  else {
    PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, 0);
    first_face_set = abs(SCULPT_face_set_get(ss, fref));
  }

  if (first_face_set == SCULPT_FACE_SET_NONE) {
    return true;
  }

  for (int f = 0; f < ss->totfaces; f++) {
    PBVHFaceRef fref = BKE_pbvh_index_to_face(ss->pbvh, f);

    int fset = SCULPT_face_set_get(ss, fref);
    fset = check_visible_only ? abs(fset) : fset;

    if (fset != first_face_set) {
      return false;
    }
  }
  return true;
}

static void sculpt_face_set_delete_geometry(Object *ob,
                                            SculptSession *ss,
                                            const int active_face_set_id,
                                            const bool modify_hidden)
{

  Mesh *mesh = (Mesh *)ob->data;
  const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(mesh);

  if (ss->bm) {
    Vector<BMFace *> faces;

    BMIter iter;
    BMFace *f;

    BM_ITER_MESH (f, &iter, ss->bm, BM_FACES_OF_MESH) {
      const int face_set_id = modify_hidden ? abs(BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset)) :
                                              BM_ELEM_CD_GET_INT(f, ss->cd_faceset_offset);
      if (face_set_id == active_face_set_id) {
        faces.append(f);
      }
    }

    for (BMFace *f : faces) {
      BKE_pbvh_bmesh_remove_face(ss->pbvh, f, true);
    }
  }
  else {
    BMeshCreateParams params = {0};
    params.use_toolflags = true;

    BMesh *bm = BM_mesh_create(&allocsize, &params);

    BMeshFromMeshParams cparams = {0};
    cparams.calc_face_normal = true;
    cparams.active_shapekey = ob->shapenr;
    cparams.use_shapekey = true;
    cparams.create_shapekey_layers = true;

    BM_mesh_bm_from_me(ob, bm, mesh, &cparams);

    BM_mesh_elem_table_init(bm, BM_FACE);
    BM_mesh_elem_table_ensure(bm, BM_FACE);
    BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
    BMIter iter;
    BMFace *f;
    BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
      const int face_index = BM_elem_index_get(f);
      const int face_set_id = modify_hidden ? abs(ss->face_sets[face_index]) :
                                              ss->face_sets[face_index];
      BM_elem_flag_set(f, BM_ELEM_TAG, face_set_id == active_face_set_id);
    }
    BM_mesh_delete_hflag_context(bm, BM_ELEM_TAG, DEL_FACES);
    BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);

    BMeshToMeshParams tparams = {0};

    BM_mesh_bm_to_me(NULL, ob, bm, (Mesh *)ob->data, &tparams);

    BM_mesh_free(bm);
  }
}

static void sculpt_face_set_edit_fair_face_set(Object *ob,
                                               const int active_face_set_id,
                                               const int fair_order)
{
  SculptSession *ss = ob->sculpt;

  const int totvert = SCULPT_vertex_count_get(ss);

  Mesh *mesh = (Mesh *)ob->data;
  bool *fair_vertices = (bool *)MEM_malloc_arrayN(totvert, sizeof(bool), "fair vertices");

  SCULPT_vertex_random_access_ensure(ss);
  SCULPT_boundary_info_ensure(ob);

  for (int i = 0; i < totvert; i++) {
    PBVHVertRef vref = BKE_pbvh_index_to_vertex(ss->pbvh, i);

    fair_vertices[i] = !SCULPT_vertex_is_boundary(ss, vref, SCULPT_BOUNDARY_MESH) &&
                       SCULPT_vertex_has_face_set(ss, vref, active_face_set_id) &&
                       SCULPT_vertex_has_unique_face_set(ss, vref);
  }

  if (ss->bm) {
    BKE_bmesh_prefair_and_fair_verts(ss->bm, fair_vertices, (eMeshFairingDepth)fair_order);
  }
  else {
    MVert *mvert = SCULPT_mesh_deformed_mverts_get(ss);
    BKE_mesh_prefair_and_fair_verts(mesh, mvert, fair_vertices, (eMeshFairingDepth)fair_order);

    MEM_freeN(fair_vertices);
  }
}

static void sculpt_face_set_apply_edit(Object *ob,
                                       const int active_face_set_id,
                                       const int mode,
                                       const bool modify_hidden)
{
  SculptSession *ss = ob->sculpt;

  switch (mode) {
    case SCULPT_FACE_SET_EDIT_GROW: {
      int *prev_face_sets = ss->face_sets ? (int *)MEM_dupallocN(ss->face_sets) : NULL;
      sculpt_face_set_grow(ob, ss, prev_face_sets, active_face_set_id, modify_hidden);
      MEM_SAFE_FREE(prev_face_sets);
      break;
    }
    case SCULPT_FACE_SET_EDIT_SHRINK: {
      int *prev_face_sets = ss->face_sets ? (int *)MEM_dupallocN(ss->face_sets) : NULL;
      sculpt_face_set_shrink(ob, ss, prev_face_sets, active_face_set_id, modify_hidden);
      MEM_SAFE_FREE(prev_face_sets);
      break;
    }
    case SCULPT_FACE_SET_EDIT_FILL_COMPONENT: {
      sculpt_face_set_fill_component(ob, ss, active_face_set_id, modify_hidden);
      break;
    }
    case SCULPT_FACE_SET_EDIT_DELETE_GEOMETRY:
      sculpt_face_set_delete_geometry(ob, ss, active_face_set_id, modify_hidden);
      break;
    case SCULPT_FACE_SET_EDIT_FAIR_POSITIONS:
      sculpt_face_set_edit_fair_face_set(ob, active_face_set_id, MESH_FAIRING_DEPTH_POSITION);
      break;
    case SCULPT_FACE_SET_EDIT_FAIR_TANGENCY:
      sculpt_face_set_edit_fair_face_set(ob, active_face_set_id, MESH_FAIRING_DEPTH_TANGENCY);
      break;
    case SCULPT_FACE_SET_EDIT_FAIR_ALL_TANGENCY: {
      GSet *face_sets_ids = BLI_gset_int_new("ids");
      for (int i = 0; i < ss->totfaces; i++) {
        BLI_gset_add(face_sets_ids, POINTER_FROM_INT(ss->face_sets[i]));
      }

      GSetIterator gs_iter;
      GSET_ITER (gs_iter, face_sets_ids) {
        const int face_set_id = POINTER_AS_INT(BLI_gsetIterator_getKey(&gs_iter));
        sculpt_face_set_edit_fair_face_set(ob, face_set_id, MESH_FAIRING_DEPTH_TANGENCY);
      }

      BLI_gset_free(face_sets_ids, NULL);
    } break;
    case SCULPT_FACE_SET_EDIT_FAIR_CURVATURE:
      sculpt_face_set_edit_fair_face_set(ob, active_face_set_id, MESH_FAIRING_DEPTH_CURVATURE);
      break;
  }
}

static bool sculpt_face_set_edit_is_operation_valid(SculptSession *ss,
                                                    const eSculptFaceSetEditMode mode,
                                                    const bool modify_hidden)
{
  SCULPT_vertex_random_access_ensure(ss);
  SCULPT_face_random_access_ensure(ss);

  if (ELEM(mode, SCULPT_FACE_SET_EDIT_DELETE_GEOMETRY, SCULPT_FACE_SET_EDIT_EXTRUDE)) {
    if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) {
      /* Modification of base mesh geometry requires special remapping of multires displacement,
       * which does not happen here.
       * Disable delete operation. It can be supported in the future by doing similar
       * displacement data remapping as what happens in the mesh edit mode. */
      return false;
    }
    if (check_single_face_set(ss, !modify_hidden)) {
      /* Cancel the operator if the mesh only contains one Face Set to avoid deleting the
       * entire object. */
      return false;
    }
  }

  if (ELEM(mode, SCULPT_FACE_SET_EDIT_FAIR_POSITIONS, SCULPT_FACE_SET_EDIT_FAIR_TANGENCY)) {
    if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) {
      /* TODO: Multires topology representation using grids and duplicates can't be used directly
       * by the fair algorithm. Multires topology needs to be exposed in a different way or
       * converted to a mesh for this operation. */
      return false;
    }
  }

  return true;
}

static void sculpt_face_set_edit_modify_geometry(bContext *C,
                                                 Object *ob,
                                                 const int active_face_set,
                                                 const eSculptFaceSetEditMode mode,
                                                 const bool modify_hidden,
                                                 wmOperator *op)
{
  ED_sculpt_undo_geometry_begin(ob, op);
  sculpt_face_set_apply_edit(ob, abs(active_face_set), mode, modify_hidden);
  ED_sculpt_undo_geometry_end(ob);
  BKE_mesh_batch_cache_dirty_tag((Mesh *)ob->data, BKE_MESH_BATCH_DIRTY_ALL);
  DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
  WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
}

static void face_set_edit_do_post_visibility_updates(Object *ob, PBVHNode **nodes, int totnode)
{
  SculptSession *ss = ob->sculpt;
  PBVH *pbvh = ss->pbvh;

  BKE_pbvh_update_vertex_data(ss->pbvh, PBVH_UpdateVisibility);

  if (BKE_pbvh_type(pbvh) == PBVH_FACES) {
    BKE_mesh_flush_hidden_from_verts((Mesh *)ob->data);
  }
}

static void sculpt_face_set_edit_modify_face_sets(Object *ob,
                                                  const int active_face_set,
                                                  const eSculptFaceSetEditMode mode,
                                                  const bool modify_hidden,
                                                  wmOperator *op)
{
  PBVH *pbvh = ob->sculpt->pbvh;
  PBVHNode **nodes;
  int totnode;
  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);

  if (!nodes) {
    return;
  }
  SCULPT_undo_push_begin(ob, op);
  SCULPT_undo_push_node(ob, nodes[0], SCULPT_UNDO_FACE_SETS);
  sculpt_face_set_apply_edit(ob, abs(active_face_set), mode, modify_hidden);
  SCULPT_undo_push_end(ob);
  face_set_edit_do_post_visibility_updates(ob, nodes, totnode);
  MEM_freeN(nodes);
}

static void sculpt_face_set_edit_modify_coordinates(bContext *C,
                                                    Object *ob,
                                                    const int active_face_set,
                                                    const eSculptFaceSetEditMode mode,
                                                    wmOperator *op)
{
  Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
  SculptSession *ss = ob->sculpt;
  PBVH *pbvh = ss->pbvh;
  PBVHNode **nodes;
  int totnode;
  BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);
  SCULPT_undo_push_begin(ob, op);
  for (int i = 0; i < totnode; i++) {
    BKE_pbvh_node_mark_update(nodes[i]);
    SCULPT_undo_push_node(ob, nodes[i], SCULPT_UNDO_COORDS);
  }
  sculpt_face_set_apply_edit(ob, abs(active_face_set), mode, false);

  if (ss->deform_modifiers_active || ss->shapekey_active) {
    SCULPT_flush_stroke_deform(sd, ob, true);
  }
  SCULPT_flush_update_step(C, SCULPT_UPDATE_COORDS);
  SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_COORDS);
  SCULPT_undo_push_end(ob);
  MEM_freeN(nodes);
}

typedef struct FaceSetExtrudeCD {
  int active_face_set;
  float cursor_location[3];
  float (*orig_co)[3];
  float init_mval[2];
  float (*orig_no)[3];
  int *verts;
  int totvert;
  float start_no[3];
} FaceSetExtrudeCD;

static void sculpt_bm_mesh_elem_hflag_disable_all(BMesh *bm, char htype, char hflag)
{
  static int iters[3] = {BM_VERTS_OF_MESH, BM_EDGES_OF_MESH, BM_FACES_OF_MESH};
  static int types[3] = {BM_VERT, BM_EDGE, BM_FACE};

  for (int i = 0; i < 3; i++) {
    int type = types[i];

    if (!(htype & type)) {
      continue;
    }

    BMIter iter;
    BMElem *elem;

    BM_ITER_MESH (elem, &iter, bm, iters[i]) {
      // do not call bm selection api
      // BM_elem_select_set(bm, elem, false);

      elem->head.hflag &= ~hflag;
    }
  }
}

static void sculpt_face_set_extrude_id(Object *ob,
                                       bool no_islands,
                                       SculptSession *ss,
                                       const int active_face_set_id,
                                       FaceSetExtrudeCD *fsecd)
{

  Mesh *mesh = (Mesh *)ob->data;
  int next_face_set_id = SCULPT_face_set_next_available_get(ss) + 1;

  SculptFaceSetIsland *island = NULL;

  if (no_islands && ss->active_face.i != PBVH_REF_NONE) {
    island = SCULPT_face_set_island_get(ss, ss->active_face, active_face_set_id);

    /* convert PBVHFaceRef list into simple integers, only need to do for pbvh_bmesh*/
    if (island && ss->bm) {
      SCULPT_face_random_access_ensure(ss);

      for (int i = 0; i < island->totface; i++) {
        BMFace *f = (BMFace *)island->faces[i].i;
        island->faces[i].i = BM_elem_index_get(f);
      }
    }
  }

  no_islands = no_islands && island != NULL;

  BMesh *bm = sculpt_faceset_bm_begin(ob, ss, mesh);
  if (ss->bm) {
    BKE_pbvh_bmesh_set_toolflags(ss->pbvh, true);
    BKE_sculptsession_update_attr_refs(ob);
  }

  BM_mesh_elem_table_init(bm, BM_FACE);
  BM_mesh_elem_table_ensure(bm, BM_FACE);

  sculpt_bm_mesh_elem_hflag_disable_all(
      bm, BM_ALL_NOLOOP, BM_ELEM_SELECT | BM_ELEM_TAG_ALT | BM_ELEM_TAG);

  BMIter iter;
  BMFace *f;

  if (ss->bm && ss->pbvh) {
    BKE_pbvh_set_bm_log(ss->pbvh, ss->bm_log);
  }

  BM_mesh_select_mode_set(bm, SCE_SELECT_FACE);

  int mupdateflag = SCULPTVERT_NEED_BOUNDARY | SCULPTVERT_NEED_DISK_SORT |
                    SCULPTVERT_NEED_TRIANGULATE | SCULPTVERT_NEED_VALENCE;

  Vector<BMVert *> retvs, vs;
  Vector<BMEdge *> es;

  int cd_faceset_offset = CustomData_get_offset_named(
      &bm->pdata, CD_PROP_INT32, ".sculpt_face_sets");

  const int tag1 = BM_ELEM_SELECT;
  const int tag2 = BM_ELEM_TAG_ALT;
  const int tag3 = BM_ELEM_TAG;

  int totface = no_islands ? island->totface : bm->totface;
  for (int i = 0; i < totface; i++) {
    BMFace *f = no_islands ? bm->ftable[island->faces[i].i] : bm->ftable[i];

    const int face_set_id = BM_ELEM_CD_GET_INT(f, cd_faceset_offset);

    if (face_set_id == active_face_set_id) {
      BM_elem_select_set(bm, (BMElem *)f, true);

      if (ss->bm) {
        BMLoop *l = f->l_first;

        do {
          if (!(BM_elem_flag_test(l->e, tag2))) {
            BM_elem_flag_enable(l->e, tag2);
            es.append(l->e);
          }

          if (!(BM_elem_flag_test(l->v, tag2))) {
            BM_elem_flag_enable(l->v, tag2);
            vs.append(l->v);
          }

        } while ((l = l->next) != f->l_first);

        if (ss->bm) {
          BKE_pbvh_bmesh_remove_face(ss->pbvh, f, true);
        }
      }
    }
    else {
      BM_elem_select_set(bm, (BMElem *)f, false);
    }

    BM_elem_flag_set(f, BM_ELEM_TAG, face_set_id == active_face_set_id);
  }

  Vector<BMFace *> borderfs;
  Vector<BMEdge *> borderes;
  Vector<BMVert *> bordervs;

  if (ss->bm) {
    for (BMEdge *e : es) {
      BMLoop *l = e->l;

      bool remove = true;
      do {
        if (!(BM_elem_flag_test(l->f, tag1))) {
          // remove = false;
          borderes.append(e);
          break;
        }
      } while ((l = l->radial_next) != e->l);

      if (remove) {
        if (!BM_elem_flag_test(e->v1, tag3)) {
          BM_log_vert_removed(ss->bm_log, e->v1, ss->cd_vert_mask_offset);
          // BKE_pbvh_bmesh_remove_vertex(ss->pbvh, e->v1, true);
          BM_elem_flag_enable(e->v1, tag3);
        }

        if (!BM_elem_flag_test(e->v2, tag3)) {
          BM_log_vert_removed(ss->bm_log, e->v2, ss->cd_vert_mask_offset);
          // BKE_pbvh_bmesh_remove_vertex(ss->pbvh, e->v2, true);
          BM_elem_flag_enable(e->v2, tag3);
        }

        BKE_pbvh_bmesh_remove_edge(ss->pbvh, e, true);
        e->head.hflag |= tag1;
      }
    }

    for (BMVert *v : vs) {
      BMEdge *e = v->e;
      bool remove = true;

      do {
        if (!BM_elem_flag_test(e, tag1)) {
          // remove = false;
          bordervs.append(v);
          break;
        }
      } while ((e = BM_DISK_EDGE_NEXT(e, v)) != v->e);

      if (BM_elem_flag_test(v, tag3)) {
        continue;
      }

      BM_elem_flag_enable(v, tag3);

      if (remove) {
        // BKE_pbvh_bmesh_remove_vertex(ss->pbvh, v, true);
        BM_log_vert_removed(ss->bm_log, v, ss->cd_vert_mask_offset);
      }
    }
  }

  for (BMVert *v : bordervs) {
    BMFace *f2;
    BMIter iter;

    BM_ITER_ELEM (f2, &iter, v, BM_FACES_OF_VERT) {
      if (BM_elem_flag_test(f2, tag1) || BM_elem_flag_test(f2, tag2)) {
        continue;
      }

      if (ss->bm) {
        BKE_pbvh_bmesh_remove_face(ss->pbvh, f2, true);
      }

      BM_elem_flag_enable(f2, tag2);
      borderfs.append(f2);
    }
  }

  BM_mesh_select_flush(bm);
  BM_mesh_select_mode_flush(bm);

  BMOperator extop;
  BMO_op_init(bm, &extop, BMO_FLAG_DEFAULTS, "extrude_face_region");
  BMO_slot_bool_set(extop.slots_in, "use_normal_from_adjacent", true);
  BMO_slot_bool_set(extop.slots_in, "use_dissolve_ortho_edges", true);
  BMO_slot_bool_set(extop.slots_in, "use_select_history", true);
  char htype = BM_ALL_NOLOOP;
  htype &= ~(BM_VERT | BM_EDGE);
  if (htype & BM_FACE) {
    htype |= BM_EDGE;
  }

  BMO_slot_buffer_from_enabled_hflag(bm, &extop, extop.slots_in, "geom", htype, BM_ELEM_SELECT);

  BMO_op_exec(bm, &extop);
  sculpt_bm_mesh_elem_hflag_disable_all(
      bm, BM_ALL_NOLOOP, BM_ELEM_SELECT | BM_ELEM_TAG_ALT | BM_ELEM_TAG);

  int cd_sculpt_vert = CustomData_get_offset(&bm->vdata, CD_DYNTOPO_VERT);
  cd_faceset_offset = CustomData_get_offset_named(
      &bm->pdata, CD_PROP_INT32, ".sculpt_face_sets");  // recalc in case bmop changed it

  BMOIter siter;
  BMElem *ele;

  if (ss->bm) { /* handle some pbvh stuff */
    for (int step = 0; step < 2; step++) {
      BMO_ITER (ele, &siter, extop.slots_out, step ? "side_geom.out" : "geom.out", BM_ALL_NOLOOP) {
        if (ele->head.htype == BM_VERT) {
          BM_ELEM_CD_SET_INT(ele, ss->cd_vert_node_offset, DYNTOPO_NODE_NONE);
        }
        else if (ele->head.htype == BM_FACE) {
          BM_ELEM_CD_SET_INT(ele, ss->cd_face_node_offset, DYNTOPO_NODE_NONE);
        }
      }
    }

    /*push a log subentry*/
    BM_log_entry_add_ex(bm, ss->bm_log, true);
  }

  for (int step = 0; step < 2; step++) {
    BMO_ITER (ele, &siter, extop.slots_out, step ? "side_geom.out" : "geom.out", BM_ALL_NOLOOP) {
      if (step == 0 && ele->head.htype != BM_VERT) {
        BM_elem_flag_set(ele, BM_ELEM_TAG, true);
      }

      if (step == 1 && ele->head.htype == BM_FACE) {
        BM_ELEM_CD_SET_INT(ele, cd_faceset_offset, next_face_set_id);
      }

      if (BM_elem_flag_test(ele, tag1)) {
        continue;
      }

      BM_elem_flag_enable(ele, tag1);

      switch (ele->head.htype) {
        case BM_VERT:
          if (ss->bm) {
            BM_log_vert_added(ss->bm_log, (BMVert *)ele, ss->cd_vert_mask_offset);
          }

          if (step == 0) {
            retvs.append((BMVert *)ele);
          }

          break;
        case BM_EDGE: {
          BMEdge *e = (BMEdge *)ele;

          if (ss->bm) {
            BM_log_edge_added(ss->bm_log, e);

            if (!BM_elem_flag_test(e->v1, tag1)) {
              BM_elem_flag_enable(e->v1, tag1);
              BM_log_vert_added(ss->bm_log, e->v1, ss->cd_vert_mask_offset);
            }

            if (!BM_elem_flag_test(e->v2, tag1)) {
              BM_elem_flag_enable(e->v2, tag1);
              BM_log_vert_added(ss->bm_log, e->v2, ss->cd_vert_mask_offset);
            }

            if (1 || step == 1) {
              BMLoop *l = e->l;

              if (l) {
                do {
                  if (!BM_elem_flag_test(l->f, tag1)) {
                    BKE_pbvh_bmesh_add_face(ss->pbvh, l->f, false, false);
                    BM_log_face_added(ss->bm_log, l->f);
                  }

                  BM_elem_flag_enable(l->f, tag1);
                } while ((l = l->radial_next) != e->l);
              }
            }
          }
          break;
        }
        case BM_FACE: {
          BMFace *f = (BMFace *)ele;

          if (cd_sculpt_vert != -1) {
            BMLoop *l = f->l_first;
            do {
              MSculptVert *mv = BKE_PBVH_SCULPTVERT(cd_sculpt_vert, l->v);
              MV_ADD_FLAG(mv, mupdateflag);
            } while ((l = l->next) != f->l_first);
          }

          if (ss->bm) {
            BKE_pbvh_bmesh_add_face(ss->pbvh, f, true, false);
          }

          break;
        }
        default:
          break;
      }
    }
  }

#if 0 
  for (int i=0; i<BLI_array_len(flipfs); i++) {
    BMFace *f = flipfs[i];

    //BM_face_normal_flip(bm, f);

    if (ss->bm) {
      BKE_pbvh_bmesh_add_face(ss->pbvh, f, false, false);
      BM_log_face_added(ss->bm_log, f);
    }
  }
#endif

  BMO_op_finish(bm, &extop);

  for (BMFace *f : borderfs) {
    if (BM_elem_is_free((BMElem *)f, BM_FACE)) {
      continue;
    }

    if (cd_sculpt_vert >= 0) {
      BMLoop *l = f->l_first;
      do {
        MSculptVert *mv = BKE_PBVH_SCULPTVERT(cd_sculpt_vert, l->v);
        MV_ADD_FLAG(mv, mupdateflag);
      } while ((l = l->next) != f->l_first);
    }

    if (ss->bm && !BM_elem_flag_test(f, tag1)) {
      BKE_pbvh_bmesh_add_face(ss->pbvh, f, true, false);
    }

    BM_elem_flag_enable(f, tag1);
  }

  for (BMVert *v : retvs) {
    BM_elem_flag_enable(v, BM_ELEM_TAG);
  }

  /* Set the new Face Set ID for the extrusion. */
  const int cd_face_sets_offset = CustomData_get_offset_named(
      &bm->pdata, CD_PROP_INT32, ".sculpt_face_sets");

  BM_mesh_elem_table_ensure(bm, BM_FACE);
  BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
    const int face_set_id = BM_ELEM_CD_GET_INT(f, cd_face_sets_offset);
    if (abs(face_set_id) == active_face_set_id) {
      continue;
    }

    const int cd_sculpt_vert = CustomData_get_offset(&bm->vdata, CD_DYNTOPO_VERT);

    BMLoop *l = f->l_first;
    int count = 0;

    do {
      if (cd_sculpt_vert >= 0) {
        MSculptVert *mv = (MSculptVert *)BM_ELEM_CD_GET_VOID_P(l->v, cd_sculpt_vert);

        MV_ADD_FLAG(mv, mupdateflag);
      }

      if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
        count++;
      }
    } while ((l = l->next) != f->l_first);
  }

  BM_mesh_elem_hflag_enable_all(bm, BM_FACE, BM_ELEM_TAG, false);

  /*
  BMO_op_callf(bm,
               (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
               "recalc_face_normals faces=%hf",
               BM_ELEM_TAG);
  */

  BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
  BM_mesh_elem_hflag_disable_all(bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);

  fsecd->verts = (int *)MEM_malloc_arrayN(retvs.size(), sizeof(int), "face set extrude verts");
  fsecd->totvert = retvs.size();

  fsecd->orig_co = static_cast<float(*)[3]>(
      MEM_malloc_arrayN(retvs.size(), sizeof(float) * 3, "face set extrude verts"));
  fsecd->orig_no = static_cast<float(*)[3]>(
      MEM_malloc_arrayN(retvs.size(), sizeof(float) * 3, "face set extrude verts"));

  BM_mesh_elem_index_ensure(bm, BM_VERT | BM_EDGE | BM_FACE);

  for (int i = 0; i < retvs.size(); i++) {
    BMVert *v = retvs[i];

    fsecd->verts[i] = v->head.index;
    copy_v3_v3(fsecd->orig_co[i], v->co);

    BMIter iter;
    BMFace *f;

    float no[3] = {0.0f, 0.0f, 0.0f};

    BM_ITER_ELEM (f, &iter, v, BM_FACES_OF_VERT) {
      int fset = BM_ELEM_CD_GET_INT(f, cd_faceset_offset);
      if (fset == active_face_set_id) {
        add_v3_v3(no, f->no);
      }
    }

    normalize_v3(no);
    copy_v3_v3(fsecd->orig_no[i], no);
  }

  if (island) {
    SCULPT_face_set_island_free(island);
  }

  if (!ss->bm) {
    BMeshToMeshParams params = {0};

    BM_mesh_bm_to_me(NULL, NULL, bm, (Mesh *)ob->data, &params);
  }

  sculpt_faceset_bm_end(ss, bm);

  if (ss->bm) {
    // slow! BKE_pbvh_bmesh_set_toolflags(ss->pbvh, false);
    BKE_sculptsession_update_attr_refs(ob);
  }
}

static void island_stack_bmesh_do(
    SculptSession *ss, int fset, PBVHFaceRef face, Vector<PBVHFaceRef> &faces, BLI_bitmap *visit)
{
  BMFace *f = (BMFace *)face.i;

  BMLoop *l = f->l_first;
  do {
    BMLoop *l2 = l;

    do {
      int index = BM_elem_index_get(l2->f);

      bool ok = !BLI_BITMAP_TEST(visit, index);
      ok = ok && abs(BM_ELEM_CD_GET_INT(l2->f, ss->cd_faceset_offset)) == fset;

      if (ok) {
        BLI_BITMAP_SET(visit, index, true);

        faces.append(BKE_pbvh_make_fref((intptr_t)l2->f));
      }
    } while ((l2 = l2->radial_next) != l);
  } while ((l = l->next) != f->l_first);
}

static void island_stack_mesh_do(
    SculptSession *ss, int fset, PBVHFaceRef face, Vector<PBVHFaceRef> &faces, BLI_bitmap *visit)
{
  const MPoly *mp = ss->mpoly + face.i;
  const MLoop *ml = ss->mloop + mp->loopstart;

  for (int i = 0; i < mp->totloop; i++, ml++) {
    MeshElemMap *ep = ss->epmap + ml->e;

    for (int j = 0; j < ep->count; j++) {
      int f2 = ep->indices[j];

      if (abs(ss->face_sets[f2]) == fset && !BLI_BITMAP_TEST(visit, f2)) {
        BLI_BITMAP_SET(visit, f2, true);
        PBVHFaceRef face2 = {f2};

        faces.append(face2);
      }
    }
  }
}

SculptFaceSetIslands *SCULPT_face_set_islands_get(SculptSession *ss, int fset)
{
  if (BKE_pbvh_type(ss->pbvh) != PBVH_BMESH && !ss->epmap) {
    BKE_mesh_edge_poly_map_create(&ss->epmap,
                                  &ss->epmap_mem,
                                  ss->medge,
                                  ss->totedges,
                                  ss->mpoly,
                                  ss->totfaces,
                                  ss->mloop,
                                  ss->totloops);
  }

  SculptFaceSetIslands *ret = (SculptFaceSetIslands *)MEM_callocN(sizeof(*ret), "fset islands");
  Vector<SculptFaceSetIsland> islands;

  int totface = ss->totfaces;
  BLI_bitmap *visit = BLI_BITMAP_NEW(totface, __func__);
  Vector<PBVHFaceRef> stack;

  SCULPT_face_random_access_ensure(ss);

  for (int i = 0; i < totface; i++) {
    PBVHFaceRef face = BKE_pbvh_index_to_face(ss->pbvh, i);

    if (abs(SCULPT_face_set_get(ss, face)) != fset) {
      continue;
    }

    if (BLI_BITMAP_TEST(visit, i)) {
      continue;
    }

    BLI_BITMAP_SET(visit, i, true);

    stack.resize(0);
    stack.append(face);

    Vector<PBVHFaceRef> faces;

    while (stack.size() > 0) {
      // can't use BLI_array_pop since it doesn't work with popping structures
      PBVHFaceRef face2 = stack.pop_last();
      faces.append(face2);

      int tot = stack.size();

      if (ss->bm) {
        island_stack_bmesh_do(ss, fset, face2, stack, visit);
      }
      else {
        island_stack_mesh_do(ss, fset, face2, stack, visit);
      }
    }

    PBVHFaceRef *cfaces = (PBVHFaceRef *)MEM_malloc_arrayN(
        faces.size(), sizeof(PBVHFaceRef), __func__);
    memcpy((void *)cfaces, (void *)faces.data(), sizeof(PBVHFaceRef) * faces.size());

    SculptFaceSetIsland island;

    island.faces = cfaces;
    island.totface = faces.size();

    islands.append(island);
  }

  SculptFaceSetIsland *cislands = (SculptFaceSetIsland *)MEM_malloc_arrayN(
      islands.size(), sizeof(SculptFaceSetIsland *), __func__);
  memcpy((void *)cislands, (void *)islands.data(), sizeof(SculptFaceSetIsland *) * islands.size());

  ret->islands = cislands;
  ret->totisland = islands.size();

  MEM_SAFE_FREE(visit);
  return ret;
}

void SCULPT_face_set_islands_free(SculptSession *ss, SculptFaceSetIslands *islands)
{
  for (int i = 0; i < islands->totisland; i++) {
    MEM_SAFE_FREE(islands->islands[i].faces);
  }

  MEM_SAFE_FREE(islands->islands);
  MEM_SAFE_FREE(islands);
}

SculptFaceSetIsland *SCULPT_face_set_island_get(SculptSession *ss, PBVHFaceRef face, int fset)
{
  SculptFaceSetIslands *islands = SCULPT_face_set_islands_get(ss, fset);

  for (int i = 0; i < islands->totisland; i++) {
    SculptFaceSetIsland *island = islands->islands + i;

    for (int j = 0; j < island->totface; j++) {
      if (island->faces[j].i == face.i) {
        SculptFaceSetIsland *ret = (SculptFaceSetIsland *)MEM_callocN(sizeof(SculptFaceSetIsland),
                                                                      "SculptFaceSetIsland");

        *ret = *island;

        // prevent faces from freeing
        island->faces = NULL;

        SCULPT_face_set_islands_free(ss, islands);
        return ret;
      }
    }
  }

  SCULPT_face_set_islands_free(ss, islands);
  return NULL;
}

void SCULPT_face_set_island_free(SculptFaceSetIsland *island)
{
  if (island) {
    MEM_SAFE_FREE(island->faces);
    MEM_freeN(island);
  }
}

static int sculpt_face_set_edit_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;
  const int mode = RNA_enum_get(op->ptr, "mode");
  Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);
  BKE_sculpt_update_object_for_edit(depsgraph, ob, true, false, false);

  if (mode != SCULPT_FACE_SET_EDIT_EXTRUDE) {
    return OPERATOR_FINISHED;
  }

  if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
    FaceSetExtrudeCD *fsecd = (FaceSetExtrudeCD *)op->customdata;
    MEM_SAFE_FREE(fsecd->orig_co);
    MEM_SAFE_FREE(fsecd->orig_no);
    MEM_SAFE_FREE(fsecd->verts);
    MEM_SAFE_FREE(op->customdata);

    if (ss->bm) {
      SCULPT_undo_push_end(ob);
    }
    else {
      ED_sculpt_undo_geometry_end(ob);
    }

    SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_COORDS);
    return OPERATOR_FINISHED;
  }

  FaceSetExtrudeCD *fsecd = (FaceSetExtrudeCD *)op->customdata;
  ViewContext vc;
  ED_view3d_viewcontext_init(C, &vc, depsgraph);

  float depth_world_space[3];
  float new_pos[3];

  mul_v3_m4v3(depth_world_space, ob->obmat, fsecd->cursor_location);

  float fmval[2] = {(float)event->mval[0], (float)event->mval[1]};

  ED_view3d_win_to_3d(vc.v3d, vc.region, depth_world_space, fmval, new_pos);
  float extrude_disp = len_v3v3(depth_world_space, new_pos);

  SCULPT_vertex_random_access_ensure(ss);
  SCULPT_face_random_access_ensure(ss);

  if (dot_v3v3(fsecd->start_no, fsecd->start_no) == 0.0f && ss->active_face.i != PBVH_REF_NONE) {
    float fno[4];

    SCULPT_face_normal_get(ss, ss->active_face, fno);
    fno[3] = 0.0f;

    mul_v4_m4v4(fno, ob->obmat, fno);
    copy_v3_v3(fsecd->start_no, fno);
    // extrude_disp *= -1.0f;
  }

  float grabtan[3];
  sub_v3_v3v3(grabtan, new_pos, depth_world_space);
  if (dot_v3v3(fsecd->start_no, fsecd->start_no) > 0.0f &&
      dot_v3v3(grabtan, fsecd->start_no) < 0) {
    extrude_disp *= -1.0f;
  }

  if (!ss->bm) {
    MVert *mvert = SCULPT_mesh_deformed_mverts_get(ss);
    for (int i = 0; i < fsecd->totvert; i++) {
      int idx = fsecd->verts[i];

      madd_v3_v3v3fl(mvert[idx].co, fsecd->orig_co[i], fsecd->orig_no[i], extrude_disp);
      BKE_pbvh_vert_tag_update_normal(ss->pbvh, BKE_pbvh_make_vref(idx));
    }

    PBVHNode **nodes;
    int totnode;
    BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
    for (int i = 0; i < totnode; i++) {
      BKE_pbvh_node_mark_update(nodes[i]);
    }
    MEM_SAFE_FREE(nodes);
  }
  else {
    BM_mesh_elem_index_ensure(ss->bm, BM_VERT | BM_EDGE | BM_FACE);

    for (int i = 0; i < fsecd->totvert; i++) {
      PBVHVertRef vertex = BKE_pbvh_index_to_vertex(ss->pbvh, fsecd->verts[i]);

      BMVert *v = (BMVert *)vertex.i;

      int ni = BM_ELEM_CD_GET_INT(v, ss->cd_vert_node_offset);
      if (ni != DYNTOPO_NODE_NONE) {
        BKE_pbvh_node_mark_update(BKE_pbvh_node_from_index(ss->pbvh, ni));
      }

      madd_v3_v3v3fl(v->co, fsecd->orig_co[i], fsecd->orig_no[i], extrude_disp);
    }
  }

  SCULPT_flush_update_step(C, SCULPT_UPDATE_COORDS);
  return OPERATOR_RUNNING_MODAL;
}

static void sculpt_face_set_extrude(bContext *C,
                                    wmOperator *op,
                                    const wmEvent *event,
                                    Object *ob,
                                    const int active_face_set,
                                    const float cursor_location[3])
{
  FaceSetExtrudeCD *fsecd = (FaceSetExtrudeCD *)MEM_callocN(sizeof(FaceSetExtrudeCD),
                                                            "face set extrude cd");

  fsecd->active_face_set = active_face_set;
  copy_v3_v3(fsecd->cursor_location, cursor_location);
  float fmval[2] = {(float)event->mval[0], (float)event->mval[1]};
  copy_v2_v2(fsecd->init_mval, fmval);
  op->customdata = fsecd;

  bool no_islands = RNA_boolean_get(op->ptr, "single_island_only");

  if (!ob->sculpt->bm) {
    ED_sculpt_undo_geometry_begin(ob, op);
  }
  else {
    SCULPT_undo_push_begin(ob, op);
    SCULPT_undo_push_node(ob, NULL, SCULPT_UNDO_COORDS);
  }

  sculpt_face_set_extrude_id(ob, no_islands, ob->sculpt, active_face_set, fsecd);

  if (!ob->sculpt->bm) {
    BKE_mesh_batch_cache_dirty_tag((Mesh *)ob->data, BKE_MESH_BATCH_DIRTY_ALL);
    DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
  }

  WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
}

static int sculpt_face_set_edit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
  Object *ob = CTX_data_active_object(C);
  SculptSession *ss = ob->sculpt;
  Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);

  const int mode = RNA_enum_get(op->ptr, "mode");
  const bool modify_hidden = RNA_boolean_get(op->ptr, "modify_hidden");

  if (!sculpt_face_set_edit_is_operation_valid(ss, (eSculptFaceSetEditMode)mode, modify_hidden)) {
    return OPERATOR_CANCELLED;
  }

  ss->face_sets = BKE_sculpt_face_sets_ensure(ob);
  BKE_sculpt_update_object_for_edit(depsgraph, ob, true, false, false);

  /* Update the current active Face Set and Vertex as the operator can be used directly from the
   * tool without brush cursor. */
  SculptCursorGeometryInfo sgi;
  const float mval_fl[2] = {float(event->mval[0]), float(event->mval[1])};
  if (!SCULPT_cursor_geometry_info_update(C, &sgi, mval_fl, false, false)) {
    /* The cursor is not over the mesh. Cancel to avoid editing the last updated Face Set ID. */
    return OPERATOR_CANCELLED;
  }

  const int active_face_set = SCULPT_active_face_set_get(ss);

  switch (mode) {
    case SCULPT_FACE_SET_EDIT_EXTRUDE:
      sculpt_face_set_extrude(C, op, event, ob, active_face_set, sgi.location);

      SCULPT_tag_update_overlays(C);
      WM_event_add_modal_handler(C, op);
      return OPERATOR_RUNNING_MODAL;
    case SCULPT_FACE_SET_EDIT_DELETE_GEOMETRY:
      sculpt_face_set_edit_modify_geometry(
          C, ob, active_face_set, (eSculptFaceSetEditMode)mode, modify_hidden, op);
      break;
    case SCULPT_FACE_SET_EDIT_GROW:
    case SCULPT_FACE_SET_EDIT_SHRINK:
    case SCULPT_FACE_SET_EDIT_FILL_COMPONENT:
      sculpt_face_set_edit_modify_face_sets(
          ob, active_face_set, (eSculptFaceSetEditMode)mode, modify_hidden, op);
      break;
    case SCULPT_FACE_SET_EDIT_FAIR_POSITIONS:
    case SCULPT_FACE_SET_EDIT_FAIR_TANGENCY:
    case SCULPT_FACE_SET_EDIT_FAIR_CURVATURE:
    case SCULPT_FACE_SET_EDIT_FAIR_ALL_TANGENCY:
      sculpt_face_set_edit_modify_coordinates(
          C, ob, active_face_set, (eSculptFaceSetEditMode)mode, op);
      break;
  }

  SCULPT_tag_update_overlays(C);

  return OPERATOR_FINISHED;
}

void SCULPT_OT_face_sets_edit(struct wmOperatorType *ot)
{
  /* Identifiers. */
  ot->name = "Edit Face Set";
  ot->idname = "SCULPT_OT_face_set_edit";
  ot->description = "Edits the current active Face Set";

  /* Api callbacks. */
  ot->invoke = sculpt_face_set_edit_invoke;
  ot->modal = sculpt_face_set_edit_modal;
  ot->poll = SCULPT_mode_poll;

  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(
      ot->srna, "mode", prop_sculpt_face_sets_edit_types, SCULPT_FACE_SET_EDIT_GROW, "Mode", "");
  ot->prop = RNA_def_boolean(ot->srna,
                             "modify_hidden",
                             true,
                             "Modify Hidden",
                             "Apply the edit operation to hidden Face Sets");
  ot->prop = RNA_def_boolean(ot->srna,
                             "single_island_only",
                             false,
                             "Ignore Disconnected",
                             "Apply the edit operation to a single island only");
}