dear-implot3d-sys 0.15.1

Low-level FFI bindings for ImPlot3D via cimplot3d (C API)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
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
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz

// ImPlot3D v0.4

// Acknowledgments:
//  ImPlot3D is heavily inspired by ImPlot
//  (https://github.com/epezent/implot) by Evan Pezent,
//  and follows a similar code style and structure to
//  maintain consistency with ImPlot's API.

// Table of Contents:
// [SECTION] Includes
// [SECTION] Macros
// [SECTION] Context
// [SECTION] Text Utils
// [SECTION] Legend Utils
// [SECTION] Mouse Position Utils
// [SECTION] Plot Box Utils
// [SECTION] Formatter
// [SECTION] Locator
// [SECTION] Context Menus
// [SECTION] Begin/End Plot
// [SECTION] Setup
// [SECTION] Plot Utils
// [SECTION] Setup Utils
// [SECTION] Miscellaneous
// [SECTION] Styles
// [SECTION] Colormaps
// [SECTION] Context Utils
// [SECTION] Style Utils
// [SECTION] ImPlot3DPoint
// [SECTION] ImPlot3DBox
// [SECTION] ImPlot3DRange
// [SECTION] ImPlot3DQuat
// [SECTION] ImDrawList3D
// [SECTION] ImPlot3DAxis
// [SECTION] ImPlot3DPlot
// [SECTION] ImPlot3DStyle
// [SECTION] Metrics
// [SECTION] Obsolete API

/*
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all
implot3d files. You can read releases logs https://github.com/brenocq/implot3d/releases for more details.

- 2026/04/04 (0.4) - PlotMesh signature changed: the ImPlot3DPoint* overload is deprecated and will be removed in v1.0.
                     A new overload accepting separate coordinate arrays (vtx_xs, vtx_ys, vtx_zs) was added, matching
                     the pattern of PlotLine/PlotScatter/PlotTriangle and supporting Spec.Offset and Spec.Stride.
                         ```cpp
                         // Before
                         ImPlot3D::PlotMesh("Mesh", vtx, idxs, vtx_count, idx_count);

                         // After
                         ImPlot3D::PlotMesh("Mesh", vtx_xs, vtx_ys, vtx_zs, idxs, vtx_count, idx_count);
                         ```
- 2026/02/03 (0.4) - ImPlotSpec was made the default and _only_ way of styling plot items. The SetNextXXXStyle functions have been removed.
                      - SetNextLineStyle has been removed, styling should be set via ImPlot3DSpec.
                          ```cpp
                          // Before
                          ImPlot3D::SetNextLineStyle(line_color, line_weight);
                          ImPlot3D::PlotLine("Line", xs, ys, zs, count);

                          // After
                          ImPlot3DSpec spec;
                          spec.LineColor = line_color;
                          spec.LineWeight = line_weight;
                          ImPlot3D::PlotLine("Line", xs, ys, zs, count, spec);
                          ```
                      - SetNextFillStyle has been removed, styling should be set via ImPlot3DSpec.
                          ```cpp
                          // Before
                          ImPlot3D::SetNextFillStyle(fill_color, fill_alpha);
                          ImPlot3D::PlotTriangle("Triangle", xs, ys, zs, count);

                          // After
                          ImPlot3DSpec spec;
                          spec.FillColor = fill_color;
                          spec.FillAlpha = fill_alpha;
                          ImPlot3D::PlotTriangle("Triangle", xs, ys, zs, count, spec);
                          ```
                      - SetNextMarkerStyle has been removed, styling should be set via ImPlot3DSpec.
                          ```cpp
                          // Before:
                          ImPlot3D::SetNextMarkerStyle(marker, marker_size, fill_color, line_weight, marker_outline_color);
                          ImPlot3D::PlotScatter("Scatter", xs, ys, zs, count);

                          // After
                          ImPlot3DSpec spec;
                          spec.LineWeight = line_weight;
                          spec.Marker = marker;
                          spec.MarkerSize = marker_size;
                          spec.MarkerLineColor = marker_outline_color;
                          spec.MarkerFillColor = fill_color;
                          ImPlot3D::PlotScatter("Scatter", xs, ys, zs, count, spec);
                          ```
                      - Flags, Offset and Stride should also be set via ImPlot3DSpec now.
- 2026/02/02 (0.4) - Item colors removed from ImPlot3DCol_, it's no longer possible to push/pop individual item colors.
- 2026/02/02 (0.4) - ImPlot3DStyle::MarkerWeight was removed. The marker line weight is now controlled by ImPlot3DStyle::LineWeight.

- 2025/11/15 (0.3) - Renamed GetPlotPos() -> GetPlotRectPos() and GetPlotSize() -> GetPlotRectSize() for clarity in 3D context.
                     Old functions are marked as deprecated and will be removed in v1.0.
- 2025/10/22 (0.3) - **IMPORTANT** All plot coordinate types migrated from float to double precision to fix sorting issues with large values:
                       - ImPlot3DPoint members (x, y, z): float -> double
                       - ImPlot3DPoint operators: float parameters -> double parameters
                       - ImPlot3DRange members (Min, Max): float -> double
                       - ImPlot3DQuat members (x, y, z, w): float -> double
                       - ImPlot3DQuat methods: float parameters -> double parameters
                       - ImPlot3DTick::PlotPos: float -> double
                       - ImPlot3DAxis::NDCScale: float -> double
                       - ImDrawList3D::ZBuffer: ImVector<float> -> ImVector<double>
                       - ImDrawList3D::_ZWritePtr: float* -> double*
                       - ImPlot3DFormatter callback: float value -> double value
                       - SetupBoxRotation(): float elevation, float azimuth -> double elevation, double azimuth
                       - SetupBoxInitialRotation(): float elevation, float azimuth -> double elevation, double azimuth
                       - SetupBoxScale(): float x, float y, float z -> double x, double y, double z
                       - PlotText(): float x, float y, float z, float angle -> double x, double y, double z, double angle
                     No code changes required for most users. Advanced users directly using these classes with float precision assumption may need to
                     update their code.
- 2025/07/21 (0.3) - Renamed ImPlot3DPlot::GetBoxZoom() -> ImPlot3DPlot::GetViewScale() (internal API only).
*/

//-----------------------------------------------------------------------------
// [SECTION] Includes
//-----------------------------------------------------------------------------

#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif

// We define this to avoid accidentally using the deprecated API
#ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS
#define IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS
#endif

#include "implot3d.h"
#include "implot3d_internal.h"

#ifndef IMGUI_DISABLE

//-----------------------------------------------------------------------------
// [SECTION] Macros
//-----------------------------------------------------------------------------

#define IMPLOT3D_CHECK_CTX()                                                                                                                         \
    IM_ASSERT_USER_ERROR(GImPlot3D != nullptr, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?")
#define IMPLOT3D_CHECK_PLOT() IM_ASSERT_USER_ERROR(GImPlot3D->CurrentPlot != nullptr, "No active plot. Did you call ImPlot3D::BeginPlot()?")

//-----------------------------------------------------------------------------
// [SECTION] Context
//-----------------------------------------------------------------------------

namespace ImPlot3D {

// Global ImPlot3D context
#ifndef GImPlot3D
ImPlot3DContext* GImPlot3D = nullptr;
#endif

ImPlot3DContext* CreateContext() {
    ImPlot3DContext* ctx = IM_NEW(ImPlot3DContext)();
    if (GImPlot3D == nullptr)
        SetCurrentContext(ctx);
    InitializeContext(ctx);
    return ctx;
}

void DestroyContext(ImPlot3DContext* ctx) {
    if (ctx == nullptr)
        ctx = GImPlot3D;
    if (GImPlot3D == ctx)
        SetCurrentContext(nullptr);
    IM_DELETE(ctx);
}

ImPlot3DContext* GetCurrentContext() { return GImPlot3D; }

void SetCurrentContext(ImPlot3DContext* ctx) { GImPlot3D = ctx; }

//-----------------------------------------------------------------------------
// [SECTION] Text Utils
//-----------------------------------------------------------------------------

void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, const char* text_begin, const char* text_end) {
    if (!text_end)
        text_end = text_begin + strlen(text_begin);

    ImGuiContext& g = *GImGui;
    ImFont* font = g.Font;

#ifdef IMGUI_HAS_TEXTURES
    ImFontBaked* fontBaked = g.Font->GetFontBaked(g.FontSize);
    const float scale = g.FontSize / fontBaked->Size;
#else
    const float scale = g.FontSize / font->FontSize;
#endif

    // Align to be pixel perfect
    pos = ImFloor(pos);

    // Measure the size of the text in unrotated coordinates
    ImVec2 text_size = font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, text_begin, text_end, nullptr);

    // Precompute sine and cosine of the angle (note: angle should be positive for rotation in ImGui)
    float cos_a = cosf(-angle);
    float sin_a = sinf(-angle);

    const char* s = text_begin;
    int chars_total = (int)(text_end - s);
    int chars_rendered = 0;
    const int vtx_count_max = chars_total * 4;
    const int idx_count_max = chars_total * 6;
    draw_list->PrimReserve(idx_count_max, vtx_count_max);

    // Adjust pen position to center the text
    ImVec2 pen = ImVec2(-text_size.x * 0.5f, -text_size.y * 0.5f);

    while (s < text_end) {
        unsigned int c = (unsigned int)*s;
        if (c < 0x80) {
            s += 1;
        } else {
            s += ImTextCharFromUtf8(&c, s, text_end);
            if (c == 0) // Malformed UTF-8?
                break;
        }

#ifdef IMGUI_HAS_TEXTURES
        const ImFontGlyph* glyph = fontBaked->FindGlyph((ImWchar)c);
#else
        const ImFontGlyph* glyph = font->FindGlyph((ImWchar)c);
#endif
        if (glyph == nullptr) {
            continue;
        }

        // Glyph dimensions and positions
        ImVec2 glyph_offset = ImVec2(glyph->X0, glyph->Y0) * scale;
        ImVec2 glyph_size = ImVec2(glyph->X1 - glyph->X0, glyph->Y1 - glyph->Y0) * scale;

        // Corners of the glyph quad in unrotated space
        ImVec2 corners[4];
        corners[0] = pen + glyph_offset;
        corners[1] = pen + glyph_offset + ImVec2(glyph_size.x, 0);
        corners[2] = pen + glyph_offset + glyph_size;
        corners[3] = pen + glyph_offset + ImVec2(0, glyph_size.y);

        // Rotate and translate the corners
        for (int i = 0; i < 4; i++) {
            float x = corners[i].x;
            float y = corners[i].y;
            corners[i].x = x * cos_a - y * sin_a + pos.x;
            corners[i].y = x * sin_a + y * cos_a + pos.y;
        }

        // Texture coordinates
        ImVec2 uv0 = ImVec2(glyph->U0, glyph->V0);
        ImVec2 uv1 = ImVec2(glyph->U1, glyph->V1);

        // Render the glyph quad
        draw_list->PrimQuadUV(corners[0], corners[1], corners[2], corners[3], uv0, ImVec2(glyph->U1, glyph->V0), uv1, ImVec2(glyph->U0, glyph->V1),
                              col);

        // Advance the pen position
        pen.x += glyph->AdvanceX * scale;

        chars_rendered++;
    }

    // Return unused vertices
    int chars_skipped = chars_total - chars_rendered;
    draw_list->PrimUnreserve(chars_skipped * 6, chars_skipped * 4);
}

void AddTextCentered(ImDrawList* draw_list, ImVec2 top_center, ImU32 col, const char* text_begin) {
    const char* text_end = ImGui::FindRenderedTextEnd(text_begin);
    ImVec2 text_size = ImGui::CalcTextSize(text_begin, text_end, true);
    draw_list->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y), col, text_begin, text_end);
}

//-----------------------------------------------------------------------------
// [SECTION] Legend Utils
//-----------------------------------------------------------------------------

static const char* short_legend_location[9] = {"C", "N", "S", "W", "E", "NW", "NE", "SW", "SE"};

static const char* GetShortLegendLocationName(ImPlot3DLocation loc) {
    if (loc == ImPlot3DLocation_Center)
        return short_legend_location[0];
    if (loc == ImPlot3DLocation_North)
        return short_legend_location[1];
    if (loc == ImPlot3DLocation_South)
        return short_legend_location[2];
    if (loc == ImPlot3DLocation_West)
        return short_legend_location[3];
    if (loc == ImPlot3DLocation_East)
        return short_legend_location[4];
    if (loc == ImPlot3DLocation_NorthWest)
        return short_legend_location[5];
    if (loc == ImPlot3DLocation_NorthEast)
        return short_legend_location[6];
    if (loc == ImPlot3DLocation_SouthWest)
        return short_legend_location[7];
    if (loc == ImPlot3DLocation_SouthEast)
        return short_legend_location[8];
    return nullptr;
}

ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlot3DLocation loc, const ImVec2& pad) {
    ImVec2 pos;
    // Legend x coordinate
    if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East))
        pos.x = outer_rect.Min.x + pad.x;
    else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East))
        pos.x = outer_rect.Max.x - pad.x - inner_size.x;
    else
        pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f;
    // Legend y coordinate
    if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South))
        pos.y = outer_rect.Min.y + pad.y;
    else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South))
        pos.y = outer_rect.Max.y - pad.y - inner_size.y;
    else
        pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f;
    pos.x = IM_ROUND(pos.x);
    pos.y = IM_ROUND(pos.y);
    return pos;
}

ImVec2 CalcLegendSize(ImPlot3DItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical) {
    const int nItems = items.GetLegendCount();
    const float txt_ht = ImGui::GetTextLineHeight();
    const float icon_size = txt_ht;
    // Get label max width
    float max_label_width = 0;
    float sum_label_width = 0;
    for (int i = 0; i < nItems; i++) {
        const char* label = items.GetLegendLabel(i);
        const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
        max_label_width = label_width > max_label_width ? label_width : max_label_width;
        sum_label_width += label_width;
    }
    // Compute legend size
    const ImVec2 legend_size = vertical ? ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y)
                                        : ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht);
    return legend_size;
}

void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, const ImVec2& pad, const ImVec2& spacing, bool vertical,
                       ImDrawList& draw_list) {
    const float txt_ht = ImGui::GetTextLineHeight();
    const float icon_size = txt_ht;
    const float icon_shrink = 2;
    ImU32 col_txt = GetStyleColorU32(ImPlot3DCol_LegendText);
    ImU32 col_txt_dis = ImAlphaU32(col_txt, 0.25f);
    float sum_label_width = 0;

    const int num_items = items.GetLegendCount();
    if (num_items == 0)
        return;

    // Render legend items
    for (int i = 0; i < num_items; i++) {
        const int idx = i;
        ImPlot3DItem* item = items.GetLegendItem(idx);
        const char* label = items.GetLegendLabel(idx);
        const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
        const ImVec2 top_left = vertical ? legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y))
                                         : legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0);
        sum_label_width += label_width;
        ImRect icon_bb;
        icon_bb.Min = top_left + ImVec2(icon_shrink, icon_shrink);
        icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink);
        ImRect label_bb;
        label_bb.Min = top_left;
        label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size);
        ImU32 col_txt_hl;
        ImU32 col_item = ImAlphaU32(item->Color, 1);

        ImRect button_bb(icon_bb.Min, label_bb.Max);

        ImGui::KeepAliveID(item->ID);

        bool item_hov = false;
        bool item_hld = false;
        bool item_clk = ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoButtons)
                            ? false
                            : ImGui::ButtonBehavior(button_bb, item->ID, &item_hov, &item_hld);

        if (item_clk)
            item->Show = !item->Show;

        const bool hovering = item_hov && !ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoHighlightItem);

        if (hovering) {
            item->LegendHovered = true;
            col_txt_hl = ImPlot3D::ImMixU32(col_txt, col_item, 64);
        } else {
            item->LegendHovered = false;
            col_txt_hl = ImGui::GetColorU32(col_txt);
        }

        ImU32 col_icon;
        if (item_hld)
            col_icon = item->Show ? ImAlphaU32(col_item, 0.5f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f);
        else if (item_hov)
            col_icon = item->Show ? ImAlphaU32(col_item, 0.75f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.75f);
        else
            col_icon = item->Show ? col_item : col_txt_dis;

        draw_list.AddRectFilled(icon_bb.Min, icon_bb.Max, col_icon);
        const char* text_display_end = ImGui::FindRenderedTextEnd(label, nullptr);
        if (label != text_display_end)
            draw_list.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_txt_hl : col_txt_dis, label, text_display_end);
    }
}

void RenderLegend() {
    ImPlot3DContext& gp = *GImPlot3D;
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend) || plot.Items.GetLegendCount() == 0)
        return;
    ImGuiContext& g = *GImGui;
    ImGuiWindow* window = g.CurrentWindow;
    ImDrawList* draw_list = window->DrawList;
    const ImGuiIO& IO = ImGui::GetIO();

    ImPlot3DLegend& legend = plot.Items.Legend;
    const bool legend_horz = ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal);
    const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);
    const ImVec2 legend_pos = GetLocationPos(plot.PlotRect, legend_size, legend.Location, gp.Style.LegendPadding);
    legend.Rect = ImRect(legend_pos, legend_pos + legend_size);

    // Test hover
    legend.Hovered = legend.Rect.Contains(IO.MousePos);

    // Render background
    ImU32 col_bg = GetStyleColorU32(ImPlot3DCol_LegendBg);
    ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_LegendBorder);
    draw_list->AddRectFilled(legend.Rect.Min, legend.Rect.Max, col_bg);
    draw_list->AddRect(legend.Rect.Min, legend.Rect.Max, col_bd);

    // Render legends
    ShowLegendEntries(plot.Items, legend.Rect, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, *draw_list);
}

//-----------------------------------------------------------------------------
// [SECTION] Mouse Position Utils
//-----------------------------------------------------------------------------

void RenderMousePos() {
    ImPlot3DContext& gp = *GImPlot3D;
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoMouseText))
        return;

    ImVec2 mouse_pos = ImGui::GetMousePos();
    ImPlot3DPoint mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_YZ, true);
    if (mouse_plot_pos.IsNaN())
        mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XZ, true);
    if (mouse_plot_pos.IsNaN())
        mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XY, true);

    char buff[IMPLOT3D_LABEL_MAX_SIZE];
    if (!mouse_plot_pos.IsNaN()) {
        ImGuiTextBuffer builder;
        builder.append("(");
        for (int i = 0; i < 3; i++) {
            ImPlot3DAxis& axis = plot.Axes[i];
            if (i > 0)
                builder.append(", ");
            axis.Formatter(mouse_plot_pos[i], buff, IMPLOT3D_LABEL_MAX_SIZE, axis.FormatterData);
            builder.append(buff);
        }
        builder.append(")");

        const ImVec2 size = ImGui::CalcTextSize(builder.c_str());
        // TODO custom location/padding
        const ImVec2 pos = GetLocationPos(plot.PlotRect, size, ImPlot3DLocation_SouthEast, ImVec2(10, 10));
        ImDrawList& draw_list = *ImGui::GetWindowDrawList();
        draw_list.AddText(pos, GetStyleColorU32(ImPlot3DCol_InlayText), builder.c_str());
    }
}

//-----------------------------------------------------------------------------
// [SECTION] Plot Box Utils
//-----------------------------------------------------------------------------

// Faces of the box (defined by 4 corner indices)
static const int faces[6][4] = {
    {0, 3, 7, 4}, // X-min face
    {0, 4, 5, 1}, // Y-min face
    {0, 1, 2, 3}, // Z-min face
    {1, 2, 6, 5}, // X-max face
    {3, 7, 6, 2}, // Y-max face
    {4, 5, 6, 7}, // Z-max face
};

// Edges of the box (defined by 2 corner indices)
static const int edges[12][2] = {
    // Bottom face edges
    {0, 1},
    {1, 2},
    {2, 3},
    {3, 0},
    // Top face edges
    {4, 5},
    {5, 6},
    {6, 7},
    {7, 4},
    // Vertical edges
    {0, 4},
    {1, 5},
    {2, 6},
    {3, 7},
};

// Face edges (4 edge indices for each face)
static const int face_edges[6][4] = {
    {3, 11, 8, 7},  // X-min face
    {0, 8, 4, 9},   // Y-min face
    {0, 1, 2, 3},   // Z-min face
    {1, 9, 5, 10},  // X-max face
    {2, 10, 6, 11}, // Y-max face
    {4, 5, 6, 7},   // Z-max face
};

// Lookup table for axis_corners based on active_faces (3D plot)
static const int axis_corners_lookup_3d[8][3][2] = {
    // Index 0: active_faces = {0, 0, 0}
    {{3, 2}, {1, 2}, {1, 5}},
    // Index 1: active_faces = {0, 0, 1}
    {{7, 6}, {5, 6}, {1, 5}},
    // Index 2: active_faces = {0, 1, 0}
    {{0, 1}, {1, 2}, {2, 6}},
    // Index 3: active_faces = {0, 1, 1}
    {{4, 5}, {5, 6}, {2, 6}},
    // Index 4: active_faces = {1, 0, 0}
    {{3, 2}, {0, 3}, {0, 4}},
    // Index 5: active_faces = {1, 0, 1}
    {{7, 6}, {4, 7}, {0, 4}},
    // Index 6: active_faces = {1, 1, 0}
    {{0, 1}, {0, 3}, {3, 7}},
    // Index 7: active_faces = {1, 1, 1}
    {{4, 5}, {4, 7}, {3, 7}},
};

// Lookup table for axis_edges based on active_faces (3D plot)
static const int axis_edges_lookup_3d[8][3] = {
    // Index 0: active_faces = {0, 0, 0}
    {2, 1, 9},
    // Index 1: active_faces = {0, 0, 1}
    {6, 5, 9},
    // Index 2: active_faces = {0, 1, 0}
    {0, 1, 10},
    // Index 3: active_faces = {0, 1, 1}
    {4, 5, 10},
    // Index 4: active_faces = {1, 0, 0}
    {2, 3, 8},
    // Index 5: active_faces = {1, 0, 1}
    {6, 7, 8},
    // Index 6: active_faces = {1, 1, 0}
    {0, 3, 11},
    // Index 7: active_faces = {1, 1, 1}
    {4, 7, 11},
};

// Convert the X, Y and Z active_faces array to a integer value representation that can be looked up in axis_corners_lookup_3d
int Active3DFacesToAxisLookupIndex(const bool* active_faces) {
    return ((int)active_faces[0] << 2) | ((int)active_faces[1] << 1) | ((int)active_faces[2]);
}

int GetMouseOverPlane(const bool* active_faces, const ImVec2* corners_pix, int* plane_out = nullptr) {
    ImGuiIO& io = ImGui::GetIO();
    ImVec2 mouse_pos = io.MousePos;
    if (plane_out)
        *plane_out = -1;

    // Check each active face
    for (int a = 0; a < 3; a++) {
        int face_idx = a + 3 * active_faces[a];
        ImVec2 p0 = corners_pix[faces[face_idx][0]];
        ImVec2 p1 = corners_pix[faces[face_idx][1]];
        ImVec2 p2 = corners_pix[faces[face_idx][2]];
        ImVec2 p3 = corners_pix[faces[face_idx][3]];

        // Check if the mouse is inside the face's quad (using a triangle check)
        if (ImTriangleContainsPoint(p0, p1, p2, mouse_pos) || ImTriangleContainsPoint(p2, p3, p0, mouse_pos)) {
            if (plane_out)
                *plane_out = a;
            return a; // Return the plane index: 0 -> YZ, 1 -> XZ, 2 -> XY
        }
    }

    return -1; // Not over any active plane
}

// Check if a point is inside an edge's hover region (a rectangle extending outward from the edge)
bool IsPointInEdgeHoverRegion(const ImVec2& point, const ImVec2& p0, const ImVec2& p1, const ImVec2& outward_dir, float width) {
    ImVec2 dir = p1 - p0;
    float len = ImSqrt(ImLengthSqr(dir));
    if (len < 0.001f)
        return false;
    dir = dir / len;

    // Transform point to edge's local coordinate system
    ImVec2 local = point - p0;
    float along = local.x * dir.x + local.y * dir.y;
    float across = local.x * outward_dir.x + local.y * outward_dir.y;

    // Check if within bounds (rectangle extends from edge outward)
    return along >= 0 && along <= len && across >= 0 && across <= width;
}

// Compute the outward direction for an edge (perpendicular, pointing away from box center)
ImVec2 ComputeEdgeOutwardDir(const ImVec2& p0, const ImVec2& p1, const ImVec2& box_center) {
    ImVec2 dir = p1 - p0;
    float len = ImSqrt(ImLengthSqr(dir));
    if (len < 0.001f)
        return ImVec2(0, 0);
    dir = dir / len;

    // Perpendicular direction
    ImVec2 perp(-dir.y, dir.x);

    // Make sure it points away from box center
    ImVec2 edge_center = (p0 + p1) * 0.5f;
    ImVec2 to_edge = edge_center - box_center;
    if (ImDot(perp, to_edge) < 0)
        perp = ImVec2(-perp.x, -perp.y);

    return perp;
}

// Forward declaration
float ComputeMaxTickLabelExtent(const ImPlot3DAxis& axis);

// Spacing constants for axis tick labels and axis labels
static const float AXIS_TICK_INNER_PAD = 5.0f;  // gap between axis edge and inner edge of tick labels
static const float AXIS_LABEL_PAD = 10.0f;      // gap between tick label outer edge and axis label center
static const float AXIS_RECT_MIN_WIDTH = 40.0f; // minimum hover rect width when labels are absent

// Computes the total outward width of the hover rect for an axis
float ComputeAxisHoverWidth(const ImPlot3DAxis& axis) {
    float max_tick_extent = ComputeMaxTickLabelExtent(axis);
    float w = 2.0f * max_tick_extent + AXIS_TICK_INNER_PAD;
    if (axis.HasLabel()) {
        ImVec2 label_size = ImGui::CalcTextSize(axis.GetLabel());
        w += AXIS_LABEL_PAD + label_size.y * 0.5f;
    }
    return ImMax(w, AXIS_RECT_MIN_WIDTH);
}

int GetMouseOverAxis(const ImPlot3DPlot& plot, const ImVec2* corners_pix, const int plane_2d, const int axis_corners[3][2], int* edge_out = nullptr) {
    ImGuiIO& io = ImGui::GetIO();
    ImVec2 mouse_pos = io.MousePos;
    if (edge_out)
        *edge_out = -1;

    // Compute box center in screen space (average of all corners)
    ImVec2 box_center(0, 0);
    for (int i = 0; i < 8; i++)
        box_center = box_center + corners_pix[i];
    box_center = box_center * (1.0f / 8.0f);

    // Check each axis for mouse containment in hover rectangle
    for (int axis_idx = 0; axis_idx < 3; axis_idx++) {
        // In 2D mode, skip the perpendicular axis
        if (plane_2d != -1 && axis_idx == plane_2d)
            continue;

        int idx0 = axis_corners[axis_idx][0];
        int idx1 = axis_corners[axis_idx][1];

        // Skip if axis corners are not defined
        if (idx0 == -1 || idx1 == -1)
            continue;

        // Find the edge index for these two corners
        int edge = -1;
        for (int e = 0; e < 12; e++) {
            if ((edges[e][0] == idx0 && edges[e][1] == idx1) || (edges[e][0] == idx1 && edges[e][1] == idx0)) {
                edge = e;
                break;
            }
        }

        if (edge == -1)
            continue;

        ImVec2 p0 = corners_pix[idx0];
        ImVec2 p1 = corners_pix[idx1];
        ImVec2 outward_dir = ComputeEdgeOutwardDir(p0, p1, box_center);
        float hover_width = ComputeAxisHoverWidth(plot.Axes[axis_idx]);

        // Check if mouse is within the edge's hover region
        if (IsPointInEdgeHoverRegion(mouse_pos, p0, p1, outward_dir, hover_width)) {
            if (edge_out)
                *edge_out = edge;
            return axis_idx;
        }
    }

    return -1; // Not over any axis
}

void RenderPlotBackground(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d,
                          const int axis_corners[3][2]) {
    const ImVec4 col_bg = GetStyleColorVec4(ImPlot3DCol_PlotBg);
    const ImVec4 col_bg_hov = col_bg + ImVec4(0.03f, 0.03f, 0.03f, 0.0f);

    int hovered_plane = -1;
    if (!plot.Held) {
        // If the mouse is not held, highlight plane hovering when mouse over it
        hovered_plane = GetMouseOverPlane(active_faces, corners_pix);
        if (GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) != -1)
            hovered_plane = -1;
    } else {
        // If the mouse is held, highlight the held plane
        hovered_plane = plot.HeldPlaneIdx;
    }

    for (int a = 0; a < 3; a++) {
        int idx[4]; // Corner indices
        for (int i = 0; i < 4; i++)
            idx[i] = faces[a + 3 * active_faces[a]][i];
        const ImU32 col = ImGui::ColorConvertFloat4ToU32((hovered_plane == a) ? col_bg_hov : col_bg);
        draw_list->AddQuadFilled(corners_pix[idx[0]], corners_pix[idx[1]], corners_pix[idx[2]], corners_pix[idx[3]], col);
    }
}

void RenderAxisRects(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool*, const int plane_2d,
                     const int axis_corners[3][2]) {
    int hovered_axis = GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners);

    // Compute box center in screen space
    ImVec2 box_center(0, 0);
    for (int i = 0; i < 8; i++)
        box_center = box_center + corners_pix[i];
    box_center = box_center * (1.0f / 8.0f);

    // Render axis hover rectangles
    for (int axis_idx = 0; axis_idx < 3; axis_idx++) {
        // In 2D mode, skip the perpendicular axis
        if (plane_2d != -1 && axis_idx == plane_2d)
            continue;

        int idx0 = axis_corners[axis_idx][0];
        int idx1 = axis_corners[axis_idx][1];

        if (idx0 == -1 || idx1 == -1)
            continue;

        const ImPlot3DAxis& axis = plot.Axes[axis_idx];
        ImVec2 p0 = corners_pix[idx0];
        ImVec2 p1 = corners_pix[idx1];
        ImVec2 outward_dir = ComputeEdgeOutwardDir(p0, p1, box_center);
        float hover_width = ComputeAxisHoverWidth(axis);

        // Determine color based on state:
        // Active only when the drag started on this axis rect (HeldEdgeIdx set), not on a plane or outside.
        ImU32 col;
        if (axis.Held && plot.HeldEdgeIdx != -1)
            col = axis.ColorAct;
        else if (axis_idx == hovered_axis && !plot.Held)
            col = axis.ColorHov;
        else
            col = axis.ColorBg;

        // Draw hover rectangle if color is not transparent
        if (col != IM_COL32_BLACK_TRANS) {
            ImVec2 c0 = p0;
            ImVec2 c1 = p0 + outward_dir * hover_width;
            ImVec2 c2 = p1 + outward_dir * hover_width;
            ImVec2 c3 = p1;
            draw_list->AddQuadFilled(c0, c1, c2, c3, col);
        }
    }
}

void RenderPlotBorder(ImDrawList* draw_list, const ImPlot3DPlot&, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d) {
    // Determine which edges to render (all visible edges)
    bool render_edge[12];
    for (int i = 0; i < 12; i++)
        render_edge[i] = false;
    for (int a = 0; a < 3; a++) {
        int face_idx = a + 3 * active_faces[a];
        if (plane_2d != -1 && a != plane_2d)
            continue;
        for (size_t i = 0; i < 4; i++)
            render_edge[face_edges[face_idx][i]] = true;
    }

    // Render edge lines (all visible edges)
    ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_PlotBorder);
    for (int i = 0; i < 12; i++) {
        if (render_edge[i]) {
            int idx0 = edges[i][0];
            int idx1 = edges[i][1];
            draw_list->AddLine(corners_pix[idx0], corners_pix[idx1], col_bd, 1.0f);
        }
    }
}

void RenderGrid(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const bool* active_faces, const int plane_2d) {
    ImVec4 col_grid = GetStyleColorVec4(ImPlot3DCol_AxisGrid);
    ImU32 col_grid_minor = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.3f));
    ImU32 col_grid_major = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.6f));
    for (int face = 0; face < 3; face++) {
        if (plane_2d != -1 && face != plane_2d)
            continue;
        int face_idx = face + 3 * active_faces[face];
        const ImPlot3DAxis& axis_u = plot.Axes[(face + 1) % 3];
        const ImPlot3DAxis& axis_v = plot.Axes[(face + 2) % 3];

        // Get the two axes (u and v) that define the face plane
        int idx0 = faces[face_idx][0];
        int idx1 = faces[face_idx][1];
        int idx3 = faces[face_idx][3];

        // Corners of the face in plot space
        ImPlot3DPoint p0 = corners[idx0];
        ImPlot3DPoint p1 = corners[idx1];
        ImPlot3DPoint p3 = corners[idx3];

        // Vectors along the edges
        ImPlot3DPoint u_vec = p1 - p0;
        ImPlot3DPoint v_vec = p3 - p0;

        // Render grid lines along u axis (axis_u)
        if (!ImPlot3D::ImHasFlag(axis_u.Flags, ImPlot3DAxisFlags_NoGridLines))
            for (int t = 0; t < axis_u.Ticker.TickCount(); ++t) {
                const ImPlot3DTick& tick = axis_u.Ticker.Ticks[t];

                // Compute position along u
                double t_u = (tick.PlotPos - axis_u.Range.Min) / (axis_u.Range.Max - axis_u.Range.Min);

                // Skip ticks that are out of range
                if (t_u < 0.0 || t_u > 1.0)
                    continue;

                ImPlot3DPoint p_start = p0 + u_vec * t_u;
                ImPlot3DPoint p_end = p3 + u_vec * t_u;

                // Convert to pixel coordinates
                ImVec2 p_start_pix = PlotToPixels(p_start);
                ImVec2 p_end_pix = PlotToPixels(p_end);

                // Get color
                ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor;

                // Draw the grid line
                draw_list->AddLine(p_start_pix, p_end_pix, col_line);
            }

        // Render grid lines along v axis (axis_v)
        if (!ImPlot3D::ImHasFlag(axis_v.Flags, ImPlot3DAxisFlags_NoGridLines))
            for (int t = 0; t < axis_v.Ticker.TickCount(); ++t) {
                const ImPlot3DTick& tick = axis_v.Ticker.Ticks[t];

                // Compute position along v
                double t_v = (tick.PlotPos - axis_v.Range.Min) / (axis_v.Range.Max - axis_v.Range.Min);

                // Skip ticks that are out of range
                if (t_v < 0.0 || t_v > 1.0)
                    continue;

                ImPlot3DPoint p_start = p0 + v_vec * t_v;
                ImPlot3DPoint p_end = p1 + v_vec * t_v;

                // Convert to pixel coordinates
                ImVec2 p_start_pix = PlotToPixels(p_start);
                ImVec2 p_end_pix = PlotToPixels(p_end);

                // Get color
                ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor;

                // Draw the grid line
                draw_list->AddLine(p_start_pix, p_end_pix, col_line);
            }
    }
}

void RenderTickMarks(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix,
                     const int axis_corners[3][2], const int plane_2d) {
    ImU32 col_tick = GetStyleColorU32(ImPlot3DCol_AxisTick);

    auto DeterminePlaneForAxis = [&](int axis_idx) {
        if (plane_2d != -1)
            return plane_2d;
        // If no plane chosen (-1), use:
        // X or Y axis -> XY plane (2)
        // Z axis -> YZ plane (0)
        if (axis_idx == 2)
            return 1; // Z-axis use XZ plane
        else
            return 2; // X or Y-axis use XY plane
    };

    for (int a = 0; a < 3; a++) {
        const ImPlot3DAxis& axis = plot.Axes[a];
        if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks))
            continue;

        int idx0 = axis_corners[a][0];
        int idx1 = axis_corners[a][1];
        if (idx0 == idx1) // axis not visible or invalid
            continue;

        ImPlot3DPoint axis_start = corners[idx0];
        ImPlot3DPoint axis_end = corners[idx1];
        ImPlot3DPoint axis_dir = axis_end - axis_start;
        double axis_len = axis_dir.Length();
        if (axis_len < 1e-12)
            continue;
        axis_dir /= axis_len;

        // Draw axis line
        ImVec2 axis_start_pix = corners_pix[idx0];
        ImVec2 axis_end_pix = corners_pix[idx1];
        draw_list->AddLine(axis_start_pix, axis_end_pix, col_tick);

        // Choose plane
        int chosen_plane = DeterminePlaneForAxis(a);

        // Project axis_dir onto chosen plane
        ImPlot3DPoint proj_dir = axis_dir;
        if (chosen_plane == 0) {
            // YZ plane: zero out x
            proj_dir.x = 0.0f;
        } else if (chosen_plane == 1) {
            // XZ plane: zero out y
            proj_dir.y = 0.0f;
        } else if (chosen_plane == 2) {
            // XY plane: zero out z
            proj_dir.z = 0.0f;
        }

        double proj_len = proj_dir.Length();
        if (proj_len < 1e-12) {
            // Axis is parallel to plane normal or something degenerate, skip ticks
            continue;
        }
        proj_dir /= proj_len;

        // Rotate 90 degrees in chosen plane
        ImPlot3DPoint tick_dir;
        if (chosen_plane == 0) {
            // YZ plane
            // proj_dir=(0,py,pz), rotate 90°: (py,pz) -> (-pz,py)
            tick_dir = ImPlot3DPoint(0, -proj_dir.z, proj_dir.y);
        } else if (chosen_plane == 1) {
            // XZ plane (plane=1)
            // proj_dir=(px,0,pz), rotate 90°: (px,pz) -> (-pz,px)
            tick_dir = ImPlot3DPoint(-proj_dir.z, 0, proj_dir.x);
        } else {
            // XY plane
            // proj_dir=(px,py,0), rotate by 90°: (px,py) -> (-py,px)
            tick_dir = ImPlot3DPoint(-proj_dir.y, proj_dir.x, 0);
        }
        tick_dir.Normalize();

        // Tick lengths in NDC units
        const double major_size_ndc = 0.06;
        const double minor_size_ndc = 0.03;

        for (int t = 0; t < axis.Ticker.TickCount(); ++t) {
            const ImPlot3DTick& tick = axis.Ticker.Ticks[t];
            double v = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min);

            // Skip ticks that are out of range
            if (v < 0.0 || v > 1.0)
                continue;
            ImPlot3DPoint tick_pos_ndc = PlotToNDC(axis_start + axis_dir * (v * axis_len));

            // Half tick on each side of the axis line
            double size_tick_ndc = tick.Major ? major_size_ndc : minor_size_ndc;
            ImPlot3DPoint half_tick_ndc = tick_dir * (size_tick_ndc * 0.5);

            ImPlot3DPoint T1_ndc = tick_pos_ndc - half_tick_ndc;
            ImPlot3DPoint T2_ndc = tick_pos_ndc + half_tick_ndc;

            ImVec2 T1_screen = NDCToPixels(T1_ndc);
            ImVec2 T2_screen = NDCToPixels(T2_ndc);

            draw_list->AddLine(T1_screen, T2_screen, col_tick);
        }
    }
}

// Computes the maximum extent of tick labels perpendicular to the axis in screen space
float ComputeMaxTickLabelExtent(const ImPlot3DAxis& axis) {
    if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels))
        return 0.0f;

    // Tick labels are always rendered perpendicular to the axis (in the outward direction),
    // so LabelSize.x (the text advance width) fully contributes to the outward extent.
    float max_extent = 0.0f;
    for (int t = 0; t < axis.Ticker.TickCount(); ++t) {
        const ImPlot3DTick& tick = axis.Ticker.Ticks[t];
        if (!tick.ShowLabel)
            continue;
        max_extent = ImMax(max_extent, tick.LabelSize.x * 0.5f);
    }

    return max_extent;
}

void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix,
                      const int axis_corners[3][2]) {
    ImU32 col_tick_txt = GetStyleColorU32(ImPlot3DCol_AxisText);

    for (int a = 0; a < 3; a++) {
        const ImPlot3DAxis& axis = plot.Axes[a];
        if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels))
            continue;

        // Corner indices for this axis
        int idx0 = axis_corners[a][0];
        int idx1 = axis_corners[a][1];

        // If normal to the 2D plot, ignore the ticks
        if (idx0 == idx1)
            continue;

        // Start and end points of the axis in plot and screen space
        ImPlot3DPoint axis_start = corners[idx0];
        ImPlot3DPoint axis_dir = corners[idx1] - axis_start;
        ImVec2 axis_start_pix = corners_pix[idx0];
        ImVec2 axis_end_pix = corners_pix[idx1];

        // Screen space axis direction (normalized), needed for text angle
        ImVec2 axis_screen_dir = axis_end_pix - axis_start_pix;
        float axis_length = ImSqrt(ImLengthSqr(axis_screen_dir));
        axis_screen_dir = (axis_length > 0.0f) ? axis_screen_dir / axis_length : ImVec2(1.0f, 0.0f);

        // Outward perpendicular direction and label offset
        ImVec2 outward_dir = ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, PlotToPixels(plot.RangeCenter()));
        float max_tick_extent = ComputeMaxTickLabelExtent(axis);
        ImVec2 offset_pix = outward_dir * (max_tick_extent + AXIS_TICK_INNER_PAD);

        // Compute angle perpendicular to axis in screen space
        float angle = atan2f(-axis_screen_dir.y, axis_screen_dir.x) + IM_PI * 0.5f;

        // Normalize angle to be between -π and π
        if (angle > IM_PI)
            angle -= 2 * IM_PI;
        if (angle < -IM_PI)
            angle += 2 * IM_PI;

        // Adjust angle to keep labels upright
        if (angle > IM_PI * 0.5f)
            angle -= IM_PI;
        if (angle < -IM_PI * 0.5f)
            angle += IM_PI;

        // Loop over ticks
        for (int t = 0; t < axis.Ticker.TickCount(); ++t) {
            const ImPlot3DTick& tick = axis.Ticker.Ticks[t];
            if (!tick.ShowLabel)
                continue;

            // Compute position along the axis
            double t_axis = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min);

            // Skip ticks that are out of range
            if (t_axis < 0.0 || t_axis > 1.0)
                continue;
            ImPlot3DPoint tick_pos = axis_start + axis_dir * t_axis;

            // Convert to pixel coordinates
            ImVec2 tick_pos_pix = PlotToPixels(tick_pos);

            // Get the tick label text
            const char* label = axis.Ticker.GetText(tick);

            // Adjust label position by offset
            ImVec2 label_pos_pix = tick_pos_pix + offset_pix;

            // Render the tick label
            AddTextRotated(draw_list, label_pos_pix, angle, col_tick_txt, label);
        }
    }
}

void RenderAxisLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint*, const ImVec2* corners_pix,
                      const int axis_corners[3][2]) {
    ImU32 col_ax_txt = GetStyleColorU32(ImPlot3DCol_AxisText);

    for (int a = 0; a < 3; a++) {
        const ImPlot3DAxis& axis = plot.Axes[a];
        if (!axis.HasLabel())
            continue;

        const char* label = axis.GetLabel();

        // Corner indices
        int idx0 = axis_corners[a][0];
        int idx1 = axis_corners[a][1];

        // If normal to the 2D plot, ignore axis label
        if (idx0 == idx1)
            continue;

        ImVec2 axis_start_pix = corners_pix[idx0];
        ImVec2 axis_end_pix = corners_pix[idx1];

        // Screen space axis direction (normalized), needed for text angle
        ImVec2 axis_screen_dir = axis_end_pix - axis_start_pix;
        float axis_length = ImSqrt(ImLengthSqr(axis_screen_dir));
        axis_screen_dir = (axis_length > 0.0f) ? axis_screen_dir / axis_length : ImVec2(1.0f, 0.0f);

        // Outward perpendicular and total offset:
        // tick labels are centered at (max_tick_extent + AXIS_TICK_INNER_PAD) from the axis edge,
        // so the axis label sits one more max_tick_extent + AXIS_LABEL_PAD beyond that.
        ImVec2 outward_dir = ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, PlotToPixels(plot.RangeCenter()));
        float max_tick_extent = ComputeMaxTickLabelExtent(axis);
        float tick_label_center = max_tick_extent + AXIS_TICK_INNER_PAD;
        float total_offset = tick_label_center + max_tick_extent + AXIS_LABEL_PAD;

        ImVec2 axis_center_pix = (axis_start_pix + axis_end_pix) * 0.5f;
        ImVec2 label_pos_pix = axis_center_pix + outward_dir * total_offset;

        // Compute text angle
        float angle = atan2f(-axis_screen_dir.y, axis_screen_dir.x);
        if (angle > IM_PI * 0.5f)
            angle -= IM_PI;
        if (angle < -IM_PI * 0.5f)
            angle += IM_PI;

        AddTextRotated(draw_list, label_pos_pix, angle, col_ax_txt, label);
    }
}

// Function to compute active faces based on the rotation
// If the plot is close to 2D, plane_2d is set to the plane index (0 -> YZ, 1 -> XZ, 2 -> XY)
// plane_2d is set to -1 otherwise
void ComputeActiveFaces(bool* active_faces, const ImPlot3DQuat& rotation, const ImPlot3DAxis* axes, int* plane_2d = nullptr) {
    if (plane_2d)
        *plane_2d = -1;

    ImPlot3DPoint rot_face_n[3] = {
        rotation * ImPlot3DPoint(1.0f, 0.0f, 0.0f),
        rotation * ImPlot3DPoint(0.0f, 1.0f, 0.0f),
        rotation * ImPlot3DPoint(0.0f, 0.0f, 1.0f),
    };

    int num_deg = 0; // Check number of planes that are degenerate (seen as a line)
    for (int i = 0; i < 3; i++) {
        // Determine the active face based on the Z component
        if (fabs(rot_face_n[i].z) < 0.025) {
            // If aligned with the plane, choose the min face for bottom/left
            active_faces[i] = rot_face_n[i].x + rot_face_n[i].y < 0.0f;
            num_deg++;
        } else {
            // Otherwise, determine based on the Z component
            bool is_inverted = ImHasFlag(axes[i].Flags, ImPlot3DAxisFlags_Invert);
            active_faces[i] = is_inverted ? (rot_face_n[i].z > 0.0f) : (rot_face_n[i].z < 0.0f);
            // Set this plane as possible 2d plane
            if (plane_2d)
                *plane_2d = i;
        }
    }
    // Only return 2d plane if there are exactly 2 degenerate planes
    if (num_deg != 2 && plane_2d)
        *plane_2d = -1;
}

// Function to compute the box corners in plot space
void ComputeBoxCorners(ImPlot3DPoint* corners, const ImPlot3DPoint& range_min, const ImPlot3DPoint& range_max) {
    corners[0] = ImPlot3DPoint(range_min.x, range_min.y, range_min.z); // 0
    corners[1] = ImPlot3DPoint(range_max.x, range_min.y, range_min.z); // 1
    corners[2] = ImPlot3DPoint(range_max.x, range_max.y, range_min.z); // 2
    corners[3] = ImPlot3DPoint(range_min.x, range_max.y, range_min.z); // 3
    corners[4] = ImPlot3DPoint(range_min.x, range_min.y, range_max.z); // 4
    corners[5] = ImPlot3DPoint(range_max.x, range_min.y, range_max.z); // 5
    corners[6] = ImPlot3DPoint(range_max.x, range_max.y, range_max.z); // 6
    corners[7] = ImPlot3DPoint(range_min.x, range_max.y, range_max.z); // 7
}

// Convert a position in the plot's NDC to pixels
ImVec2 NDCToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) {
    ImVec2 center = plot.PlotRect.GetCenter();
    ImPlot3DPoint point_pix = plot.GetViewScale() * (plot.Rotation * point);
    point_pix.y *= -1.0f; // Invert y-axis
    point_pix.x += center.x;
    point_pix.y += center.y;

    return ImVec2((float)point_pix.x, (float)point_pix.y);
}

// Convert a position in the plot's coordinate system to the plot's normalized device coordinate system (NDC)
ImPlot3DPoint PlotToNDC(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) {
    ImPlot3DPoint ndc_point;
    for (int i = 0; i < 3; i++) {
        const ImPlot3DAxis& axis = plot.Axes[i];
        // Apply forward transform if needed, then normalize to [0, 1]
        double plt = point[i];
        double t;
        if (axis.TransformForward != nullptr) {
            double s = axis.TransformForward(plt, axis.TransformData);
            t = (s - axis.ScaledRange.Min) / (axis.ScaledRange.Max - axis.ScaledRange.Min);
        } else {
            t = (plt - axis.Range.Min) / (axis.Range.Max - axis.Range.Min);
        }
        // Convert point to NDC range [-0.5*NDCScale, 0.5*NDCScale]
        const double ndc_range = 0.5;
        ndc_point[i] = (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - t) : (t - ndc_range)) * axis.NDCScale;
    }
    return ndc_point;
}

// Convert a position in the plot's coordinate system to pixels
ImVec2 PlotToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { return NDCToPixels(plot, PlotToNDC(plot, point)); }

// Function to compute the box corners in pixel space
void ComputeBoxCornersPix(const ImPlot3DPlot& plot, ImVec2* corners_pix, const ImPlot3DPoint* corners) {
    for (int i = 0; i < 8; i++) {
        corners_pix[i] = PlotToPixels(plot, corners[i]);
    }
}

// Function to get axes parameters which can then be used later down the line
void GetAxesParameters(const ImPlot3DPlot& plot, bool* active_faces, ImVec2* corners_pix, ImPlot3DPoint* corners, int& plane_2d,
                       int axis_corners[3][2]) {
    // Get plot parameters
    const ImPlot3DQuat& rotation = plot.Rotation;
    ImPlot3DPoint range_min = plot.RangeMin();
    ImPlot3DPoint range_max = plot.RangeMax();

    // Compute active faces
    ComputeActiveFaces(active_faces, rotation, plot.Axes, &plane_2d);
    bool is_2d = plane_2d != -1;

    // Compute box corners in plot space
    ComputeBoxCorners(corners, range_min, range_max);

    // Compute box corners in pixel space
    ComputeBoxCornersPix(plot, corners_pix, corners);

    // Compute axes start and end corners (given current rotation)
    if (is_2d) {
        int face = plane_2d + 3 * active_faces[plane_2d]; // Face of the 2D plot
        int common_edges[2] = {-1, -1};                   // Edges shared by the 3 faces

        // Find the common edges between the 3 faces
        for (int i = 0; i < 4; i++) {
            int edge = face_edges[face][i];
            for (int j = 0; j < 2; j++) {
                int axis = (plane_2d + 1 + j) % 3;
                int face_idx = axis + active_faces[axis] * 3;
                for (int k = 0; k < 4; k++) {
                    if (face_edges[face_idx][k] == edge) {
                        common_edges[j] = edge;
                        break;
                    }
                }
            }
        }

        // Get corners from 2 edges (origin is the corner in common)
        int origin_corner = -1;
        int x_corner = -1;
        int y_corner = -1;
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                if (edges[common_edges[0]][i] == edges[common_edges[1]][j]) {
                    origin_corner = edges[common_edges[0]][i];
                    x_corner = edges[common_edges[0]][!i];
                    y_corner = edges[common_edges[1]][!j];
                }

        // Swap x and y if they are flipped
        ImVec2 x_vec = corners_pix[x_corner] - corners_pix[origin_corner];
        ImVec2 y_vec = corners_pix[y_corner] - corners_pix[origin_corner];
        if (y_vec.x > x_vec.x)
            ImSwap(x_corner, y_corner);

        // Check which 3d axis the 2d axis refers to
        ImPlot3DPoint origin_3d = corners[origin_corner];
        ImPlot3DPoint x_3d = (corners[x_corner] - origin_3d).Normalized();
        ImPlot3DPoint y_3d = (corners[y_corner] - origin_3d).Normalized();
        int x_axis = -1;
        bool x_inverted = false;
        int y_axis = -1;
        bool y_inverted = false;
        for (int i = 0; i < 2; i++) {
            int axis_i = (plane_2d + 1 + i) % 3;
            if (y_axis != -1 || (ImAbs(x_3d[axis_i]) > 1e-8f && x_axis == -1)) {
                x_axis = axis_i;
                x_inverted = x_3d[axis_i] < 0.0f;
            } else {
                y_axis = axis_i;
                y_inverted = y_3d[axis_i] < 0.0f;
            }
        }

        // Set the 3d axis corners based on the 2d axis corners
        axis_corners[plane_2d][0] = -1;
        axis_corners[plane_2d][1] = -1;
        if (x_inverted) {
            axis_corners[x_axis][0] = x_corner;
            axis_corners[x_axis][1] = origin_corner;
        } else {
            axis_corners[x_axis][0] = origin_corner;
            axis_corners[x_axis][1] = x_corner;
        }
        if (y_inverted) {
            axis_corners[y_axis][0] = y_corner;
            axis_corners[y_axis][1] = origin_corner;
        } else {
            axis_corners[y_axis][0] = origin_corner;
            axis_corners[y_axis][1] = y_corner;
        }
    } else {
        int index = Active3DFacesToAxisLookupIndex(active_faces);
        for (int a = 0; a < 3; a++) {
            axis_corners[a][0] = axis_corners_lookup_3d[index][a][0];
            axis_corners[a][1] = axis_corners_lookup_3d[index][a][1];
        }
    }
}

void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) {
    bool active_faces[3];
    ImVec2 corners_pix[8];
    ImPlot3DPoint corners[8];
    int plane_2d;
    int axis_corners[3][2];

    GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners);

    // Render components
    RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners);
    RenderAxisRects(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners);
    RenderPlotBorder(draw_list, plot, corners_pix, active_faces, plane_2d);
    RenderGrid(draw_list, plot, corners, active_faces, plane_2d);
    RenderTickMarks(draw_list, plot, corners, corners_pix, axis_corners, plane_2d);
    RenderTickLabels(draw_list, plot, corners, corners_pix, axis_corners);
    RenderAxisLabels(draw_list, plot, corners, corners_pix, axis_corners);
}

//-----------------------------------------------------------------------------
// [SECTION] Formatter
//-----------------------------------------------------------------------------

int Formatter_Default(double value, char* buff, int size, void* data) {
    char* fmt = (char*)data;
    return ImFormatString(buff, size, fmt, value);
}

//------------------------------------------------------------------------------
// [SECTION] Locator
//------------------------------------------------------------------------------

double NiceNum(double x, bool round) {
    double f;
    double nf;
    int expv = (int)floor(ImLog10(x));
    f = x / ImPow(10.0, (double)expv);
    if (round)
        if (f < 1.5)
            nf = 1;
        else if (f < 3)
            nf = 2;
        else if (f < 7)
            nf = 5;
        else
            nf = 10;
    else if (f <= 1)
        nf = 1;
    else if (f <= 2)
        nf = 2;
    else if (f <= 5)
        nf = 5;
    else
        nf = 10;
    return nf * ImPow(10.0, expv);
}

void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) {
    if (range.Min == range.Max)
        return;
    const int nMinor = ImMin(ImMax(1, (int)IM_ROUND(pixels / 30.0f)), 5);
    const int nMajor = ImMax(2, (int)IM_ROUND(pixels / 80.0f));
    const int max_ticks_labels = 7;
    const double nice_range = NiceNum(range.Size() * 0.99, false);
    const double interval = NiceNum(nice_range / (nMajor - 1), true);
    const double graphmin = floor(range.Min / interval) * interval;
    const double graphmax = ceil(range.Max / interval) * interval;
    bool first_major_set = false;
    int first_major_idx = 0;
    const int idx0 = ticker.TickCount(); // Ticker may have user custom ticks
    for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {
        // Is this zero? combat zero formatting issues
        if (major - interval < 0 && major + interval > 0)
            major = 0;
        if (range.Contains(major)) {
            if (!first_major_set) {
                first_major_idx = ticker.TickCount();
                first_major_set = true;
            }
            ticker.AddTick(major, true, true, formatter, formatter_data);
        }
        for (int i = 1; i < nMinor; i++) {
            double minor = major + i * interval / nMinor;
            if (range.Contains(minor)) {
                ticker.AddTick(minor, false, true, formatter, formatter_data);
            }
        }
    }

    // Prune tick labels
    if (ticker.TickCount() > max_ticks_labels) {
        for (int i = first_major_idx - 1; i >= idx0; i -= 2)
            ticker.Ticks[i].ShowLabel = false;
        for (int i = first_major_idx + 1; i < ticker.TickCount(); i += 2)
            ticker.Ticks[i].ShowLabel = false;
    }
}

bool CalcLogarithmicExponents(const ImPlot3DRange& range, float pix, int& exp_min, int& exp_max, int& exp_step) {
    if (range.Min * range.Max > 0) {
        const int nMajor = ImMax(2, (int)IM_ROUND(pix * 0.01f)); // TODO: magic numbers
        double log_min = ImLog10(ImAbs(range.Min));
        double log_max = ImLog10(ImAbs(range.Max));
        double log_a = ImMin(log_min, log_max);
        double log_b = ImMax(log_min, log_max);
        exp_step = ImMax(1, (int)(log_b - log_a) / nMajor);
        exp_min = (int)log_a;
        exp_max = (int)log_b;
        if (exp_step != 1) {
            while (exp_step % 3 != 0)
                exp_step++; // make step size multiple of three
            while (exp_min % exp_step != 0)
                exp_min--; // decrease exp_min until exp_min + N * exp_step will be 0
        }
        return true;
    }
    return false;
}

void AddTicksLogarithmic(const ImPlot3DRange& range, int exp_min, int exp_max, int exp_step, ImPlot3DTicker& ticker, ImPlot3DFormatter formatter,
                         void* data) {
    const double sign = ImSign(range.Max);
    for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) {
        double major1 = sign * ImPow(10, (double)(e));
        double major2 = sign * ImPow(10, (double)(e + 1));
        double interval = (major2 - major1) / 9;
        if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON))
            ticker.AddTick(major1, true, true, formatter, data);
        for (int j = 0; j < exp_step; ++j) {
            major1 = sign * ImPow(10, (double)(e + j));
            major2 = sign * ImPow(10, (double)(e + j + 1));
            interval = (major2 - major1) / 9;
            for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) {
                double minor = major1 + i * interval;
                if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON))
                    ticker.AddTick(minor, false, false, formatter, data);
            }
        }
    }
}

void Locator_Log10(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) {
    int exp_min, exp_max, exp_step;
    if (CalcLogarithmicExponents(range, pixels, exp_min, exp_max, exp_step))
        AddTicksLogarithmic(range, exp_min, exp_max, exp_step, ticker, formatter, formatter_data);
}

float CalcSymLogPixel(double plt, const ImPlot3DRange& range, float pixels) {
    double scaleToPixels = pixels / range.Size();
    double scaleMin = TransformForward_SymLog(range.Min, nullptr);
    double scaleMax = TransformForward_SymLog(range.Max, nullptr);
    double s = TransformForward_SymLog(plt, nullptr);
    double t = (s - scaleMin) / (scaleMax - scaleMin);
    plt = range.Min + range.Size() * t;

    return (float)(0 + scaleToPixels * (plt - range.Min));
}

void Locator_SymLog(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) {
    if (range.Min >= -1 && range.Max <= 1)
        Locator_Default(ticker, range, pixels, formatter, formatter_data);
    else if (range.Min * range.Max < 0) { // cross zero
        const float pix_min = 0;
        const float pix_max = pixels;
        const float pix_p1 = CalcSymLogPixel(1, range, pixels);
        const float pix_n1 = CalcSymLogPixel(-1, range, pixels);
        int exp_min_p, exp_max_p, exp_step_p;
        int exp_min_n, exp_max_n, exp_step_n;
        CalcLogarithmicExponents(ImPlot3DRange(1, range.Max), ImAbs(pix_max - pix_p1), exp_min_p, exp_max_p, exp_step_p);
        CalcLogarithmicExponents(ImPlot3DRange(range.Min, -1), ImAbs(pix_n1 - pix_min), exp_min_n, exp_max_n, exp_step_n);
        int exp_step = ImMax(exp_step_n, exp_step_p);
        ticker.AddTick(0, true, true, formatter, formatter_data);
        AddTicksLogarithmic(ImPlot3DRange(1, range.Max), exp_min_p, exp_max_p, exp_step, ticker, formatter, formatter_data);
        AddTicksLogarithmic(ImPlot3DRange(range.Min, -1), exp_min_n, exp_max_n, exp_step, ticker, formatter, formatter_data);
    } else {
        Locator_Log10(ticker, range, pixels, formatter, formatter_data);
    }
}

void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlot3DTicker& ticker, ImPlot3DFormatter formatter, void* data) {
    for (int i = 0; i < n; i++) {
        if (labels != nullptr)
            ticker.AddTick(values[i], false, true, labels[i]);
        else
            ticker.AddTick(values[i], false, true, formatter, data);
    }
}

//------------------------------------------------------------------------------
// [SECTION] Context Menus
//------------------------------------------------------------------------------

static const char* axis_contexts[3] = {"##XAxisContext", "##YAxisContext", "##ZAxisContext"};
static const char* axis_labels[3] = {"X-Axis", "Y-Axis", "Z-Axis"};
static const char* plane_contexts[3] = {"##YZPlaneContext", "##XZPlaneContext", "##XYPlaneContext"};
static const char* plane_labels[3] = {"YZ-Plane", "XZ-Plane", "XY-Plane"};

bool ShowLegendContextMenu(ImPlot3DLegend& legend, bool visible) {
    const float s = ImGui::GetFrameHeight();
    bool ret = false;
    if (ImGui::Checkbox("Show", &visible))
        ret = true;
    if (ImGui::RadioButton("H", ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal)))
        legend.Flags |= ImPlot3DLegendFlags_Horizontal;
    ImGui::SameLine();
    if (ImGui::RadioButton("V", !ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal)))
        legend.Flags &= ~ImPlot3DLegendFlags_Horizontal;
    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2));
    // clang-format off
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthWest; } ImGui::SameLine();
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_North) , ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_North;     } ImGui::SameLine();
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthEast), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthEast; }
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_West), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_West;      } ImGui::SameLine();
    if (ImGui::InvisibleButton(GetShortLegendLocationName(ImPlot3DLocation_Center), ImVec2(1.5f*s,s))) {     } ImGui::SameLine();
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_East), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_East;      }
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthWest; } ImGui::SameLine();
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_South), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_South;     } ImGui::SameLine();
    if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthEast),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthEast; }
    // clang-format on
    ImGui::PopStyleVar();
    return ret;
}

void ShowAxisContextMenu(ImPlot3DPlot& plot, ImAxis3D axis_id) {
    ImGui::PushItemWidth(75);
    ImPlot3DAxis& axis = plot.Axes[axis_id];
    bool always_locked = axis.IsRangeLocked() || axis.IsAutoFitting();
    bool label = axis.HasLabel();
    bool grid = axis.HasGridLines();
    bool ticks = axis.HasTickMarks();
    bool labels = axis.HasTickLabels();
    double drag_speed =
        (axis.Range.Size() <= DBL_EPSILON) ? DBL_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // Recover from almost equal axis limits
    const bool equal_aspect = ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_Equal);

    ImGui::BeginDisabled(always_locked);
    ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMin);
    ImGui::EndDisabled();
    ImGui::SameLine();

    ImGui::BeginDisabled(axis.IsLockedMin() || always_locked);
    double temp_min = axis.Range.Min;
    if (ImGui::DragScalar("Min", ImGuiDataType_Double, &temp_min, (float)drag_speed, &axis.ConstraintRange.Min, &axis.Range.Max)) {
        axis.SetMin(temp_min, true);
        // Apply equal aspect if needed
        if (equal_aspect)
            plot.ApplyEqualAspect(axis_id);
    }
    ImGui::EndDisabled();

    ImGui::BeginDisabled(always_locked);
    ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMax);
    ImGui::EndDisabled();
    ImGui::SameLine();
    ImGui::BeginDisabled(axis.IsLockedMax() || always_locked);
    double temp_max = axis.Range.Max;
    if (ImGui::DragScalar("Max", ImGuiDataType_Double, &temp_max, (float)drag_speed, &axis.Range.Min, &axis.ConstraintRange.Max)) {
        axis.SetMax(temp_max, true);
        // Apply equal aspect if needed
        if (equal_aspect)
            plot.ApplyEqualAspect(axis_id);
    }
    ImGui::EndDisabled();

    ImGui::Separator();

    // Flags
    ImGui::CheckboxFlags("Auto-Fit", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_AutoFit);
    ImGui::Separator();

    bool inverted = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert);
    if (ImGui::Checkbox("Invert", &inverted))
        ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_Invert);

    ImGui::Separator();

    ImGui::BeginDisabled(axis.Label.empty());
    if (ImGui::Checkbox("Label", &label))
        ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoLabel);
    ImGui::EndDisabled();

    if (ImGui::Checkbox("Grid Lines", &grid))
        ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoGridLines);
    if (ImGui::Checkbox("Tick Marks", &ticks))
        ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks);
    if (ImGui::Checkbox("Tick Labels", &labels))
        ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels);
}

void ShowPlaneContextMenu(ImPlot3DPlot& plot, int plane_idx) {
    for (int i = 0; i < 3; i++) {
        if (i == plane_idx)
            continue;
        ImPlot3DAxis& axis = plot.Axes[i];
        ImGui::PushID(i);
        if (ImGui::BeginMenu(axis.HasLabel() ? axis.GetLabel() : axis_labels[i])) {
            ShowAxisContextMenu(plot, i);
            ImGui::EndMenu();
        }
        ImGui::PopID();
    }
}

void ShowPlotContextMenu(ImPlot3DPlot& plot) {
    char buf[16] = {};
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];
        ImGui::PushID(i);
        ImFormatString(buf, sizeof(buf) - 1, i == 0 ? "X-Axis" : "X-Axis %d", i + 1);
        if (ImGui::BeginMenu(axis.HasLabel() ? axis.GetLabel() : axis_labels[i])) {
            ShowAxisContextMenu(plot, i);
            ImGui::EndMenu();
        }
        ImGui::PopID();
    }

    ImGui::Separator();

    if ((ImGui::BeginMenu("Box"))) {
        ImGui::PushItemWidth(75);
        float temp_scale[3] = {(float)plot.Axes[0].NDCScale, (float)plot.Axes[1].NDCScale, (float)plot.Axes[2].NDCScale};
        if (ImGui::DragFloat("Scale X", &temp_scale[0], 0.01f, 0.1f, 3.0f))
            plot.Axes[0].NDCScale = ImMax(temp_scale[0], 0.01f);
        if (ImGui::DragFloat("Scale Y", &temp_scale[1], 0.01f, 0.1f, 3.0f))
            plot.Axes[1].NDCScale = ImMax(temp_scale[1], 0.01f);
        if (ImGui::DragFloat("Scale Z", &temp_scale[2], 0.01f, 0.1f, 3.0f))
            plot.Axes[2].NDCScale = ImMax(temp_scale[2], 0.01f);
        ImGui::PopItemWidth();
        ImGui::EndMenu();
    }

    ImGui::Separator();

    if ((ImGui::BeginMenu("Legend"))) {
        if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend)))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend);
        ImGui::EndMenu();
    }

    if ((ImGui::BeginMenu("Settings"))) {
        if (ImGui::MenuItem("Equal", nullptr, ImHasFlag(plot.Flags, ImPlot3DFlags_Equal)))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_Equal);
        ImGui::BeginDisabled(plot.Title.empty());
        if (ImGui::MenuItem("Title", nullptr, plot.HasTitle()))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_NoTitle);
        ImGui::EndDisabled();
        if (ImGui::MenuItem("Clip", nullptr, !ImHasFlag(plot.Flags, ImPlot3DFlags_NoClip)))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_NoClip);
        if (ImGui::MenuItem("Mouse Position", nullptr, !ImHasFlag(plot.Flags, ImPlot3DFlags_NoMouseText)))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_NoMouseText);
        ImGui::EndMenu();
    }
}

//-----------------------------------------------------------------------------
// [SECTION] Begin/End Plot
//-----------------------------------------------------------------------------

bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) {
    IMPLOT3D_CHECK_CTX();
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "Mismatched BeginPlot()/EndPlot()!");

    // Get window
    ImGuiContext& g = *GImGui;
    ImGuiWindow* window = g.CurrentWindow;

    // Skip if needed
    if (window->SkipItems)
        return false;

    // Get or create plot
    const ImGuiID ID = window->GetID(title_id);
    const bool just_created = gp.Plots.GetByKey(ID) == nullptr;
    gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID);
    gp.CurrentItems = &gp.CurrentPlot->Items;
    ImPlot3DPlot& plot = *gp.CurrentPlot;

    // Populate plot
    plot.ID = ID;
    plot.JustCreated = just_created;
    if (just_created) {
        plot.Rotation = plot.InitialRotation;
        plot.FitThisFrame = true;
        for (int i = 0; i < 3; i++) {
            plot.Axes[i] = ImPlot3DAxis();
            plot.Axes[i].FitThisFrame = true;
        }
    }
    if (plot.PreviousFlags != flags)
        plot.Flags = flags;
    plot.PreviousFlags = flags;
    plot.SetupLocked = false;
    plot.OpenContextThisFrame = false;
    plot.RotationCond = ImPlot3DCond_None;

    // Populate title
    plot.SetTitle(title_id);

    // Calculate frame size
    ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);
    if (frame_size.x < gp.Style.PlotMinSize.x && size.x < 0.0f)
        frame_size.x = gp.Style.PlotMinSize.x;
    if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f)
        frame_size.y = gp.Style.PlotMinSize.y;

    // Create plot ImGui item
    plot.FrameRect = ImRect(window->DC.CursorPos, window->DC.CursorPos + frame_size);
    ImGui::ItemSize(plot.FrameRect);
    if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect)) {
        gp.CurrentPlot = nullptr;
        gp.CurrentItems = nullptr;
        gp.CurrentItem = nullptr;
        return false;
    }

    // Reset legend
    plot.Items.Legend.Reset();

    // Reset axes
    for (int i = 0; i < ImAxis3D_COUNT; i++)
        plot.Axes[i].Reset();

    // Push frame rect clipping
    ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);
    plot.DrawList._Flags = window->DrawList->Flags;
    plot.DrawList._SharedData = ImGui::GetDrawListSharedData();

    return true;
}

void EndPlot() {
    IMPLOT3D_CHECK_CTX();
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Mismatched BeginPlot()/EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;

    // Move triangles from 3D draw list to ImGui draw list
    plot.DrawList.SortedMoveToImGuiDrawList();

    // Handle data fitting
    if (plot.FitThisFrame) {
        plot.FitThisFrame = false;

        const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal);
        if (!axis_equal) {
            // Apply fit to all axes independently
            for (int i = 0; i < 3; i++) {
                if (plot.Axes[i].FitThisFrame) {
                    plot.Axes[i].FitThisFrame = false;
                    plot.Axes[i].ApplyFit();
                }
            }
        } else {
            // Find the fitted axis with the highest aspect ratio (units per NDC unit) after fit
            // This axis will require the most space and should be used as reference
            ImAxis3D ref_axis = ImAxis3D_X;
            double max_aspect = 0.0;

            // First, apply fit to all axes
            for (int i = 0; i < 3; i++) {
                if (plot.Axes[i].FitThisFrame) {
                    plot.Axes[i].FitThisFrame = false;
                    plot.Axes[i].ApplyFit();

                    // Get aspect ratio for this axis
                    double aspect = plot.Axes[i].GetAspect();
                    if (aspect > max_aspect) {
                        max_aspect = aspect;
                        ref_axis = (ImAxis3D)i;
                    }
                }
            }

            // Then, apply equal aspect constraint if enabled
            // This ensures data remains centered and visible
            plot.ApplyEqualAspect(ref_axis);
        }
    }

    // Lock setup if not already done
    SetupLock();

    // Pop plot rect clipping
    ImGui::PopClipRect();

    // Reset legend hover
    plot.Items.Legend.Hovered = false;

    // Render legend
    RenderLegend();

    // Render mouse position
    RenderMousePos();

    // Legend context menu
    if (ImGui::BeginPopup("##LegendContext")) {
        ImGui::Text("Legend");
        ImGui::Separator();
        if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend)))
            ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend);
        ImGui::EndPopup();
    }

    // Axis context menus
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];
        if (ImGui::BeginPopup(axis_contexts[i])) {
            ImGui::Text(axis.HasLabel() ? axis.GetLabel() : "%c-Axis", 'X' + i);
            ImGui::Separator();
            ShowAxisContextMenu(plot, i);
            ImGui::EndPopup();
        }
    }

    // Plane context menus
    for (int i = 0; i < 3; i++) {
        if (ImGui::BeginPopup(plane_contexts[i])) {
            ImGui::Text("%s", plane_labels[i]);
            ImGui::Separator();
            ShowPlaneContextMenu(plot, i);
            ImGui::EndPopup();
        }
    }

    // Plot context menu
    if (ImGui::BeginPopup("##PlotContext")) {
        ShowPlotContextMenu(plot);
        ImGui::EndPopup();
    }

    // Pop frame rect clipping
    ImGui::PopClipRect();

    // Reset current plot
    gp.CurrentPlot = nullptr;
    gp.CurrentItems = nullptr;
    gp.CurrentItem = nullptr;

    // Reset the plot items for the next frame
    for (int i = 0; i < plot.Items.GetItemCount(); i++)
        plot.Items.GetItemByIndex(i)->SeenThisFrame = false;
}

//-----------------------------------------------------------------------------
// [SECTION] Setup
//-----------------------------------------------------------------------------

static const float ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415f;

float CalcAnimationTime(ImPlot3DQuat q0, ImPlot3DQuat q1) {
    // Compute the angular distance between orientations
    double dot_product = ImClamp(q0.Dot(q1), -1.0, 1.0);
    float angle = 2.0f * acosf(fabsf((float)dot_product));

    // Calculate animation time for constant the angular velocity
    return angle / ANIMATION_ANGULAR_VELOCITY;
}

void SetupAxis(ImAxis3D idx, const char* label, ImPlot3DAxisFlags flags) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupAxis() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!");

    // Get plot and axis
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    if (axis.PreviousFlags != flags)
        axis.Flags = flags;
    axis.PreviousFlags = flags;
    axis.SetLabel(label);
}

void SetupAxisLimits(ImAxis3D idx, double min_lim, double max_lim, ImPlot3DCond cond) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupAxisLimits() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    if (!plot.Initialized || cond == ImPlot3DCond_Always) {
        axis.SetRange(min_lim, max_lim);
        axis.RangeCond = cond;
        axis.FitThisFrame = false;
        // Apply equal aspect ratio constraint if needed
        if (ImHasFlag(plot.Flags, ImPlot3DFlags_Equal))
            plot.ApplyEqualAspect(idx);
    }
}

void SetupAxisFormat(ImAxis3D idx, ImPlot3DFormatter formatter, void* data) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.Formatter = formatter;
    axis.FormatterData = data;
}

void SetupAxisTicks(ImAxis3D idx, const double* values, int n_ticks, const char* const labels[], bool keep_default) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.ShowDefaultTicks = keep_default;
    AddTicksCustom(values, labels, n_ticks, axis.Ticker, axis.Formatter ? axis.Formatter : Formatter_Default,
                   (axis.Formatter && axis.FormatterData) ? axis.FormatterData : (void*)IMPLOT3D_LABEL_FORMAT);
}

void SetupAxisTicks(ImAxis3D idx, double v_min, double v_max, int n_ticks, const char* const labels[], bool keep_default) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    n_ticks = n_ticks < 2 ? 2 : n_ticks;
    ImVector<double> temp;
    FillRange(temp, n_ticks, v_min, v_max);
    SetupAxisTicks(idx, temp.Data, n_ticks, labels, keep_default);
}

void SetupAxisScale(ImAxis3D idx, ImPlot3DScale scale) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.Scale = scale;
    switch (scale) {
        case ImPlot3DScale_Log10:
            axis.TransformForward = TransformForward_Log10;
            axis.TransformInverse = TransformInverse_Log10;
            axis.TransformData = nullptr;
            axis.Locator = Locator_Log10;
            axis.ConstraintRange = ImPlot3DRange(FLT_MIN, INFINITY);
            break;
        case ImPlot3DScale_SymLog:
            axis.TransformForward = TransformForward_SymLog;
            axis.TransformInverse = TransformInverse_SymLog;
            axis.TransformData = nullptr;
            axis.Locator = Locator_SymLog;
            axis.ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY);
            break;
        default:
            axis.TransformForward = nullptr;
            axis.TransformInverse = nullptr;
            axis.TransformData = nullptr;
            axis.Locator = nullptr;
            axis.ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY);
            break;
    }
}

void SetupAxisScale(ImAxis3D idx, ImPlot3DTransform forward, ImPlot3DTransform inverse, void* data) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.Scale = IMPLOT3D_AUTO;
    axis.TransformForward = forward;
    axis.TransformInverse = inverse;
    axis.TransformData = data;
}

void SetupAxisLimitsConstraints(ImAxis3D idx, double v_min, double v_max) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.ConstraintRange.Min = v_min;
    axis.ConstraintRange.Max = v_max;
}

void SetupAxisZoomConstraints(ImAxis3D idx, double zoom_min, double zoom_max) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DAxis& axis = plot.Axes[idx];
    axis.ConstraintZoom.Min = zoom_min;
    axis.ConstraintZoom.Max = zoom_max;
}

void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags, ImPlot3DAxisFlags y_flags,
               ImPlot3DAxisFlags z_flags) {
    SetupAxis(ImAxis3D_X, x_label, x_flags);
    SetupAxis(ImAxis3D_Y, y_label, y_flags);
    SetupAxis(ImAxis3D_Z, z_label, z_flags);
}

void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, ImPlot3DCond cond) {
    SetupAxisLimits(ImAxis3D_X, x_min, x_max, cond);
    SetupAxisLimits(ImAxis3D_Y, y_min, y_max, cond);
    SetupAxisLimits(ImAxis3D_Z, z_min, z_max, cond);
    if (cond == ImPlot3DCond_Once)
        GImPlot3D->CurrentPlot->FitThisFrame = false;
}

void SetupBoxRotation(double elevation, double azimuth, bool animate, ImPlot3DCond cond) {
    // Convert angles from degrees to radians
    double elev_rad = elevation * IM_PI / 180.0;
    double azim_rad = azimuth * IM_PI / 180.0;

    // Call quaternion SetupBoxRotation
    SetupBoxRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad), animate, cond);
}

void SetupBoxRotation(ImPlot3DQuat rotation, bool animate, ImPlot3DCond cond) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupBoxRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;

    if (!plot.Initialized || cond == ImPlot3DCond_Always) {
        if (!animate) {
            plot.Rotation = rotation;
            plot.AnimationTime = 0.0f; // Force any running rotation animation to stop
        } else {
            plot.RotationAnimationEnd = rotation;
            plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd);
        }
        plot.RotationCond = cond;
    }
}

void SetupBoxInitialRotation(double elevation, double azimuth) {
    // Convert angles from degrees to radians
    double elev_rad = elevation * IM_PI / 180.0;
    double azim_rad = azimuth * IM_PI / 180.0;

    // Call quaternion SetupBoxInitialRotation
    SetupBoxInitialRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad));
}

void SetupBoxInitialRotation(ImPlot3DQuat rotation) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupBoxInitialRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;

    plot.InitialRotation = rotation;
}

void SetupBoxScale(double x, double y, double z) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupBoxScale() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!");
    IM_ASSERT_USER_ERROR(x > 0.0 && y > 0.0 && z > 0.0, "SetupBoxScale() requires all aspect ratios to be greater than 0!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    plot.Axes[0].NDCScale = x;
    plot.Axes[1].NDCScale = y;
    plot.Axes[2].NDCScale = z;
}

void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
                         "SetupLegend() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!");
    IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "SetupLegend() needs to be called within an itemized context!");
    ImPlot3DLegend& legend = gp.CurrentItems->Legend;
    if (legend.PreviousLocation != location)
        legend.Location = location;
    legend.PreviousLocation = location;
    if (legend.PreviousFlags != flags)
        legend.Flags = flags;
    legend.PreviousFlags = flags;
}

//-----------------------------------------------------------------------------
// [SECTION] Plot Utils
//-----------------------------------------------------------------------------

ImPlot3DPlot* GetCurrentPlot() { return GImPlot3D->CurrentPlot; }

void BustPlotCache() {
    ImPlot3DContext& gp = *GImPlot3D;
    gp.Plots.Clear();
}

ImVec2 PlotToPixels(const ImPlot3DPoint& point) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!");
    return NDCToPixels(PlotToNDC(point));
}

ImVec2 PlotToPixels(double x, double y, double z) { return PlotToPixels(ImPlot3DPoint(x, y, z)); }

ImPlot3DRay PixelsToPlotRay(const ImVec2& pix) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotRay() needs to be called between BeginPlot() and EndPlot()!");
    return NDCRayToPlotRay(PixelsToNDCRay(pix));
}

ImPlot3DRay PixelsToPlotRay(double x, double y) { return PixelsToPlotRay(ImVec2((float)x, (float)y)); }

ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotPlane() needs to be called between BeginPlot() and EndPlot()!");

    ImPlot3DPlot& plot = *gp.CurrentPlot;
    ImPlot3DRay ray = PixelsToNDCRay(pix);
    const ImPlot3DPoint& O = ray.Origin;
    const ImPlot3DPoint& D = ray.Direction;

    // Helper lambda to check intersection with a given coordinate and return intersection point if valid.
    auto IntersectPlane = [&](double coord) -> ImPlot3DPoint {
        // Solve for t in O[axis] + D[axis]*t = coord
        double denom = 0.0;
        double numer = 0.0;
        if (plane == ImPlane3D_YZ) {
            denom = D.x;
            numer = coord - O.x;
        } else if (plane == ImPlane3D_XZ) {
            denom = D.y;
            numer = coord - O.y;
        } else if (plane == ImPlane3D_XY) {
            denom = D.z;
            numer = coord - O.z;
        }

        if (ImAbs(denom) < 1e-12f) {
            // Ray is parallel or nearly parallel to the plane
            return ImPlot3DPoint(NAN, NAN, NAN);
        }

        double t = numer / denom;
        if (t < 0.0f) {
            // Intersection behind the ray origin
            return ImPlot3DPoint(NAN, NAN, NAN);
        }

        return O + D * t;
    };

    // Compute which plane to intersect with
    bool active_faces[3];
    ComputeActiveFaces(active_faces, plot.Rotation, plot.Axes);

    // Calculate intersection point with the planes
    ImPlot3DPoint P = IntersectPlane(active_faces[plane] ? 0.5f * plot.Axes[plane].NDCScale : -0.5f * plot.Axes[plane].NDCScale);
    if (P.IsNaN())
        return P;

    // Helper lambda to check if point P is within the plot box
    auto InRange = [&](const ImPlot3DPoint& P) {
        ImPlot3DPoint box_scale = plot.GetBoxScale();
        return P.x >= -0.5f * box_scale.x && P.x <= 0.5f * box_scale.x && P.y >= -0.5f * box_scale.y && P.y <= 0.5f * box_scale.y &&
               P.z >= -0.5f * box_scale.z && P.z <= 0.5f * box_scale.z;
    };

    // Handle mask (if one of the intersections is out of range, set it to NAN)
    if (mask) {
        switch (plane) {
            case ImPlane3D_YZ:
                if (!InRange(ImPlot3DPoint(0.0, P.y, P.z)))
                    return ImPlot3DPoint(NAN, NAN, NAN);
                break;
            case ImPlane3D_XZ:
                if (!InRange(ImPlot3DPoint(P.x, 0.0, P.z)))
                    return ImPlot3DPoint(NAN, NAN, NAN);
                break;
            case ImPlane3D_XY:
                if (!InRange(ImPlot3DPoint(P.x, P.y, 0.0)))
                    return ImPlot3DPoint(NAN, NAN, NAN);
                break;
        }
    }

    return NDCToPlot(P);
}

ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask) { return PixelsToPlotPlane(ImVec2((float)x, (float)y), plane, mask); }

ImVec2 GetPlotRectPos() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotRectPos() needs to be called between BeginPlot() and EndPlot()!");
    SetupLock();
    return gp.CurrentPlot->PlotRect.Min;
}

ImVec2 GetPlotRectSize() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotRectSize() needs to be called between BeginPlot() and EndPlot()!");
    SetupLock();
    return gp.CurrentPlot->PlotRect.GetSize();
}

ImVec2 GetFramePos() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFramePos() needs to be called between BeginPlot() and EndPlot()!");
    return gp.CurrentPlot->FrameRect.Min;
}

ImVec2 GetFrameSize() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFrameSize() needs to be called between BeginPlot() and EndPlot()!");
    return gp.CurrentPlot->FrameRect.GetSize();
}

ImPlot3DPoint PlotToNDC(const ImPlot3DPoint& point) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToNDC() needs to be called between BeginPlot() and EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    SetupLock();

    return PlotToNDC(plot, point);
}

ImPlot3DPoint NDCToPlot(const ImPlot3DPoint& point) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPlot() needs to be called between BeginPlot() and EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    SetupLock();

    ImPlot3DPoint plot_point;
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];
        double ndc_range = 0.5 * axis.NDCScale;
        double ndc_point = point[i];
        double t = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - ndc_point) : (ndc_point + ndc_range);
        t /= axis.NDCScale;
        plot_point[i] = axis.NDCToPlot(t);
    }
    return plot_point;
}

ImVec2 NDCToPixels(const ImPlot3DPoint& point) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPixels() needs to be called between BeginPlot() and EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    SetupLock();

    return NDCToPixels(plot, point);
}

ImPlot3DRay PixelsToNDCRay(const ImVec2& pix) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToNDCRay() needs to be called between BeginPlot() and EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    SetupLock();

    // Calculate zoom factor and plot center
    float zoom = plot.GetViewScale();
    ImVec2 center = plot.PlotRect.GetCenter();

    // Undo screen transformations to get back to NDC space
    float x = (pix.x - center.x) / zoom;
    float y = -(pix.y - center.y) / zoom; // Invert y-axis

    // Define near and far points in NDC space along the z-axis
    ImPlot3DPoint ndc_near = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, 10.0f);
    ImPlot3DPoint ndc_far = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, -10.0f);

    // Create the ray in NDC space
    ImPlot3DRay ndc_ray;
    ndc_ray.Origin = ndc_near;
    ndc_ray.Direction = (ndc_far - ndc_near).Normalized();

    return ndc_ray;
}

ImPlot3DRay NDCRayToPlotRay(const ImPlot3DRay& ray) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCRayToPlotRay() needs to be called between BeginPlot() and EndPlot()!");
    SetupLock();

    // Convert NDC origin and a point along the ray to plot coordinates
    ImPlot3DPoint plot_origin = NDCToPlot(ray.Origin);
    ImPlot3DPoint ndc_point_along_ray = ray.Origin + ray.Direction;
    ImPlot3DPoint plot_point_along_ray = NDCToPlot(ndc_point_along_ray);

    // Compute the direction in plot coordinates
    ImPlot3DPoint plot_direction = (plot_point_along_ray - plot_origin).Normalized();

    // Create the ray in plot coordinates
    ImPlot3DRay plot_ray;
    plot_ray.Origin = plot_origin;
    plot_ray.Direction = plot_direction;

    return plot_ray;
}

//-----------------------------------------------------------------------------
// [SECTION] Setup Utils
//-----------------------------------------------------------------------------

static const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f;

void HandleInput(ImPlot3DPlot& plot) {
    if (ImHasFlag(plot.Flags, ImPlot3DFlags_NoInputs))
        return;

    ImGuiIO& IO = ImGui::GetIO();

    // clang-format off
    const ImGuiButtonFlags plot_button_flags = ImGuiButtonFlags_AllowOverlap
                                             | ImGuiButtonFlags_PressedOnClick
                                             | ImGuiButtonFlags_PressedOnDoubleClick
                                             | ImGuiButtonFlags_MouseButtonLeft
                                             | ImGuiButtonFlags_MouseButtonRight
                                             | ImGuiButtonFlags_MouseButtonMiddle;
    // clang-format on
    const bool plot_clicked = ImGui::ButtonBehavior(plot.PlotRect, plot.ID, &plot.Hovered, &plot.Held, plot_button_flags);
#if (IMGUI_VERSION_NUM < 18966)
    ImGui::SetItemAllowOverlap(); // Handled by ButtonBehavior()
#endif

    // State
    const ImVec2 rot_drag = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
    const bool rotating = ImLengthSqr(rot_drag) > MOUSE_CURSOR_DRAG_THRESHOLD;
    const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal);
    const bool allow_rotate = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoRotate);
    const bool allow_pan = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoPan);
    const bool allow_zoom = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoZoom);

    // HOVERING STATE -------------------------------------------------------------------

    // Check if any axis/plane is hovered
    bool active_faces[3];
    ImVec2 corners_pix[8];
    ImPlot3DPoint corners[8];
    int plane_2d;
    int axis_corners[3][2];
    GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners);
    int hovered_plane_idx = -1;
    int hovered_plane = GetMouseOverPlane(active_faces, corners_pix, &hovered_plane_idx);
    int hovered_edge_idx = -1;
    int hovered_axis = GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners, &hovered_edge_idx);
    if (hovered_axis != -1) {
        hovered_plane_idx = -1;
        hovered_plane = -1;
    }

    // If the user is no longer pressing the translation/zoom buttons, set axes as not held
    if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && !ImGui::IsMouseDown(ImGuiMouseButton_Middle)) {
        for (int i = 0; i < 3; i++)
            plot.Axes[i].Held = false;
    }

    // Reset held edge/plane indices (it will be set if mouse button is down)
    if (!plot.Held) {
        plot.HeldEdgeIdx = -1;
        plot.HeldPlaneIdx = -1;
    }

    // Check which axes should be transformed (fit/zoom/translate)
    bool any_axis_held = plot.Axes[0].Held || plot.Axes[1].Held || plot.Axes[2].Held;
    if (!any_axis_held) {
        // Only update the transformation axes if the user is not already performing a transformation
        plot.Axes[0].Hovered = plot.Axes[1].Hovered = plot.Axes[2].Hovered = false;
        if (hovered_axis != -1) {
            plot.Axes[hovered_axis].Hovered = true;
        } else if (hovered_plane != -1) {
            plot.Axes[(hovered_plane + 1) % 3].Hovered = true;
            plot.Axes[(hovered_plane + 2) % 3].Hovered = true;
        } else {
            plot.Axes[0].Hovered = plot.Axes[1].Hovered = plot.Axes[2].Hovered = true;
        }
    }

    // Compute plane that is being hovered by mouse
    ImPlane3D mouse_plane = ImPlane3D_XY;
    if (plane_2d != -1)
        mouse_plane = plane_2d;
    else if (plot.Axes[1].Hovered && plot.Axes[2].Hovered)
        mouse_plane = ImPlane3D_YZ;
    else if (plot.Axes[0].Hovered && plot.Axes[2].Hovered)
        mouse_plane = ImPlane3D_XZ;
    else if (plot.Axes[0].Hovered && plot.Axes[1].Hovered)
        mouse_plane = ImPlane3D_XY;
    else if (plot.HeldEdgeIdx != -1 || hovered_edge_idx != -1) {
        // Single axis hovered: use the edge index and active faces to pick the visible plane
        // Each edge belongs to exactly 2 faces. We pick the active (visible) one.

        // If the user is holding an edge, use that index; otherwise, use the hovered edge index
        int curr_edge_idx = plot.HeldEdgeIdx != -1 ? plot.HeldEdgeIdx : hovered_edge_idx;

        // Map edge index to the two faces it belongs to, and corresponding plane
        // Format: {face_index, plane_enum}
        static const int edge_to_faces[12][2][2] = {
            {{1, ImPlane3D_XZ}, {2, ImPlane3D_XY}}, // Edge 0: Y-min face, Z-min face
            {{2, ImPlane3D_XY}, {3, ImPlane3D_YZ}}, // Edge 1: Z-min face, X-max face
            {{2, ImPlane3D_XY}, {4, ImPlane3D_XZ}}, // Edge 2: Z-min face, Y-max face
            {{0, ImPlane3D_YZ}, {2, ImPlane3D_XY}}, // Edge 3: X-min face, Z-min face
            {{1, ImPlane3D_XZ}, {5, ImPlane3D_XY}}, // Edge 4: Y-min face, Z-max face
            {{3, ImPlane3D_YZ}, {5, ImPlane3D_XY}}, // Edge 5: X-max face, Z-max face
            {{4, ImPlane3D_XZ}, {5, ImPlane3D_XY}}, // Edge 6: Y-max face, Z-max face
            {{0, ImPlane3D_YZ}, {5, ImPlane3D_XY}}, // Edge 7: X-min face, Z-max face
            {{0, ImPlane3D_YZ}, {1, ImPlane3D_XZ}}, // Edge 8: X-min face, Y-min face
            {{1, ImPlane3D_XZ}, {3, ImPlane3D_YZ}}, // Edge 9: Y-min face, X-max face
            {{3, ImPlane3D_YZ}, {4, ImPlane3D_XZ}}, // Edge 10: X-max face, Y-max face
            {{0, ImPlane3D_YZ}, {4, ImPlane3D_XZ}}, // Edge 11: X-min face, Y-max face
        };

        // Check which of the two faces is active (visible from camera)
        int face0 = edge_to_faces[curr_edge_idx][0][0];
        int face1 = edge_to_faces[curr_edge_idx][1][0];

        // Determine which face is active based on active_faces
        // Faces 0-2 are min faces (active when active_faces[i] == false)
        // Faces 3-5 are max faces (active when active_faces[i] == true)
        bool face0_active = (face0 < 3) ? !active_faces[face0] : active_faces[face0 - 3];
        bool face1_active = (face1 < 3) ? !active_faces[face1] : active_faces[face1 - 3];

        // Pick the plane corresponding to the active face
        if (face0_active) {
            mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][0][1];
        } else if (face1_active) {
            mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][1][1];
        } else {
            // Fallback: both could be active in some edge cases, use first one
            mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][0][1];
        }
    }
    ImVec2 mouse_pos = ImGui::GetMousePos();
    ImPlot3DPoint mouse_pos_plot = PixelsToPlotPlane(mouse_pos, mouse_plane, false);

    // AUTO FIT -------------------------------------------------------------------

    // Handle translation/zoom fit with double click
    if (plot_clicked && (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) || ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Middle)) &&
        (allow_pan && allow_zoom)) {
        plot.FitThisFrame = true;
        for (int i = 0; i < 3; i++)
            plot.Axes[i].FitThisFrame = plot.Axes[i].Hovered;
    }

    // Handle auto fit
    for (int i = 0; i < 3; i++)
        if (plot.Axes[i].IsAutoFitting()) {
            plot.FitThisFrame = true;
            plot.Axes[i].FitThisFrame = true;
        }

    // TRANSLATION -------------------------------------------------------------------

    // Handle translation with right mouse button
    if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Left) && allow_pan) {
        ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y);

        if (plot.Axes[0].Hovered && plot.Axes[1].Hovered && plot.Axes[2].Hovered) {
            // Perform unconstrained translation (translate on the viewer's plane)

            // Compute delta_pixels in 3D (invert y-axis)
            ImPlot3DPoint delta_pixels(delta.x, -delta.y, 0.0f);

            // Convert delta to NDC space
            float zoom = plot.GetViewScale();
            ImPlot3DPoint delta_NDC = plot.Rotation.Inverse() * (delta_pixels / zoom);

            // Create points in NDC space representing the new shifted range
            ImPlot3DPoint p_min_ndc, p_max_ndc;
            for (int i = 0; i < 3; i++) {
                double half_scale = 0.5 * plot.Axes[i].NDCScale;
                p_min_ndc[i] = -half_scale - delta_NDC[i];
                p_max_ndc[i] = half_scale - delta_NDC[i];
            }

            // Convert these NDC points to Plot space to get the new range
            // NDCToPlot handles axis inversions and non-linear transforms
            ImPlot3DPoint p_min_plt = NDCToPlot(p_min_ndc);
            ImPlot3DPoint p_max_plt = NDCToPlot(p_max_ndc);

            // Adjust plot range to translate the plot
            for (int i = 0; i < 3; i++) {
                if (plot.Axes[i].Hovered) {
                    double v1 = p_min_plt[i];
                    double v2 = p_max_plt[i];
                    double new_min = ImMin(v1, v2);
                    double new_max = ImMax(v1, v2);

                    bool increasing = new_min > plot.Axes[i].Range.Min;
                    if ((new_min != plot.Axes[i].Range.Min || new_max != plot.Axes[i].Range.Max) && !plot.Axes[i].IsPanLocked(increasing)) {
                        // Update axis range
                        plot.Axes[i].SetRange(new_min, new_max);
                        // Apply equal aspect ratio constraint
                        if (axis_equal)
                            plot.ApplyEqualAspect(i);
                    }
                    plot.Axes[i].Held = true;
                }
                // If no axis was held before (user started translating in this frame), set the held edge/plane indices
                if (!any_axis_held) {
                    plot.HeldEdgeIdx = hovered_edge_idx;
                    plot.HeldPlaneIdx = hovered_plane_idx;
                }
            }
        } else if (plot.Axes[0].Hovered || plot.Axes[1].Hovered || plot.Axes[2].Hovered) {
            // Translate along plane/axis
            //
            // For transforms like log scale, we use the approach from ImPlot:
            // Transform reference points with the mouse delta applied, which properly handles non-linear scales.
            // The key: use points that lie on the interaction plane, not arbitrary box corners.

            ImVec2 mouse_delta(IO.MouseDelta.x, IO.MouseDelta.y);

            // Create reference points on the interaction plane at the axis range extremes
            // We use the current mouse position as a template, then vary each axis independently
            ImPlot3DPoint ref_base = mouse_pos_plot;

            for (int i = 0; i < 3; i++) {
                if (plot.Axes[i].Hovered) {
                    ImPlot3DAxis& axis = plot.Axes[i];

                    // Create two reference points on the interaction plane:
                    // - One at the minimum of this axis
                    // - One at the maximum of this axis
                    // Keep other coordinates the same (on the plane)
                    ImPlot3DPoint p_min = ref_base;
                    ImPlot3DPoint p_max = ref_base;
                    p_min[i] = axis.Range.Min;
                    p_max[i] = axis.Range.Max;

                    // Transform to pixels, apply mouse delta, transform back
                    ImVec2 pix_min = PlotToPixels(plot, p_min);
                    ImVec2 pix_max = PlotToPixels(plot, p_max);

                    pix_min.x -= mouse_delta.x;
                    pix_min.y -= mouse_delta.y;
                    pix_max.x -= mouse_delta.x;
                    pix_max.y -= mouse_delta.y;

                    // Project back to plot space via the interaction plane
                    ImPlot3DPoint new_p_min = PixelsToPlotPlane(pix_min, mouse_plane, false);
                    ImPlot3DPoint new_p_max = PixelsToPlotPlane(pix_max, mouse_plane, false);

                    // Extract the new range for this axis
                    double new_min = new_p_min[i];
                    double new_max = new_p_max[i];

                    // Check if we should update
                    bool increasing = (new_min < axis.Range.Min);
                    if ((new_min != axis.Range.Min || new_max != axis.Range.Max) && !axis.IsPanLocked(increasing)) {
                        axis.SetRange(new_min, new_max);

                        // Apply equal aspect ratio constraint
                        if (axis_equal)
                            plot.ApplyEqualAspect(i);
                    }
                    axis.Held = true;
                }
                if (!any_axis_held) {
                    plot.HeldEdgeIdx = hovered_edge_idx;
                    plot.HeldPlaneIdx = hovered_plane_idx;
                }
            }
        }
    }

    // ROTATION -------------------------------------------------------------------

    // Handle reset rotation with left mouse double click
    if (plot.Held && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right) && !plot.IsRotationLocked() && allow_rotate) {
        plot.RotationAnimationEnd = plot.Rotation;

        // Calculate rotation to align the z-axis with the camera direction
        if (hovered_plane == -1) {
            plot.RotationAnimationEnd = plot.InitialRotation;
        } else {
            // Compute plane normal
            ImPlot3DPoint axis_normal = ImPlot3DPoint(0.0f, 0.0f, 0.0f);
            axis_normal[hovered_plane] = active_faces[hovered_plane] ? -1.0f : 1.0f;
            if (ImPlot3D::ImHasFlag(plot.Axes[hovered_plane].Flags, ImPlot3DAxisFlags_Invert))
                axis_normal[hovered_plane] *= -1;

            // Compute rotation to align the plane normal with the z-axis
            ImPlot3DQuat align_normal = ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * axis_normal, ImPlot3DPoint(0.0f, 0.0f, 1.0f));
            plot.RotationAnimationEnd = align_normal * plot.RotationAnimationEnd;

            if (hovered_plane != 2) {
                // Compute rotation to point z-axis up
                ImPlot3DQuat align_up =
                    ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 0.0f, 1.0f), ImPlot3DPoint(0.0f, 1.0f, 0.0f));
                plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd;
            } else {
                // Find the axis most aligned with the up direction
                ImPlot3DPoint up(0.0f, 1.0f, 0.0f);
                ImPlot3DPoint x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(1.0f, 0.0f, 0.0f);
                ImPlot3DPoint y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 1.0f, 0.0f);
                ImPlot3DPoint neg_x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(-1.0f, 0.0f, 0.0f);
                ImPlot3DPoint neg_y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, -1.0f, 0.0f);

                struct AxisAlignment {
                    ImPlot3DPoint axis;
                    float dot;
                };

                AxisAlignment candidates[] = {
                    {x_axis, (float)x_axis.Dot(up)},
                    {y_axis, (float)y_axis.Dot(up)},
                    {neg_x_axis, (float)neg_x_axis.Dot(up)},
                    {neg_y_axis, (float)neg_y_axis.Dot(up)},
                };

                // Find the candidate with the maximum dot product
                AxisAlignment* best_candidate = &candidates[0];
                for (int i = 1; i < 4; i++) {
                    if (candidates[i].dot > best_candidate->dot) {
                        best_candidate = &candidates[i];
                    }
                }

                // Compute the rotation to align the best candidate with the up direction
                ImPlot3DQuat align_up = ImPlot3DQuat::FromTwoVectors(best_candidate->axis, up);
                plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd;
            }
        }

        // Calculate animation time
        plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd);
    }

    // Handle rotation with left mouse dragging
    if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Right) && !plot.IsRotationLocked() && allow_rotate) {
        ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y);

        // Map delta to rotation angles (in radians)
        float angle_x = delta.x * (3.1415f / 180.0f);
        float angle_y = delta.y * (3.1415f / 180.0f);

        // If drag just started, determine and store the rotation axis
        if (plot.DragRotationAxis == ImPlot3DPoint(0.0f, 0.0f, 0.0f)) {
            ImPlot3DPoint up_vector = plot.Rotation * ImPlot3DPoint(0.0f, 0.0f, 1.0f);
            bool is_upside_down = up_vector.z < 0.0f;
            plot.DragRotationAxis = is_upside_down ? ImPlot3DPoint(0.0f, 0.0f, -1.0f) : ImPlot3DPoint(0.0f, 0.0f, 1.0f);
        }

        // Create quaternions for the rotations
        ImPlot3DQuat quat_x(angle_y, ImPlot3DPoint(1.0f, 0.0f, 0.0f));
        ImPlot3DQuat quat_z(angle_x, plot.DragRotationAxis);

        // Combine the new rotations with the current rotation
        plot.Rotation = quat_x * plot.Rotation * quat_z;
        plot.Rotation.Normalize();
    } else {
        // Reset drag rotation axis when not dragging
        plot.DragRotationAxis = ImPlot3DPoint(0.0f, 0.0f, 0.0f);
    }

    // ZOOM -------------------------------------------------------------------

    // Handle zoom with mouse wheel
    if (plot.Hovered && allow_zoom) {
        ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, plot.ID);
        if (ImGui::IsMouseDown(ImGuiMouseButton_Middle) || IO.MouseWheel != 0.0f) {
            float delta = ImGui::IsMouseDown(ImGuiMouseButton_Middle) ? (-0.01f * IO.MouseDelta.y) : (-0.1f * IO.MouseWheel);
            float zoom_rate = delta; // Positive = zoom in, negative = zoom out

            // For transforms like log scale, we use the approach from ImPlot:
            // Transform reference points with zoom expansion/contraction applied in pixel/NDC space,
            // which properly handles non-linear scales.

            const bool zoom_around_mouse = (hovered_axis != -1 || hovered_plane != -1);

            // Zoom all hovered axes independently
            ImAxis3D ref_axis = ImAxis3D_X;
            for (int i = 0; i < 3; i++) {
                if (!plot.Axes[i].Hovered || plot.Axes[i].IsInputLocked())
                    continue;

                ImPlot3DAxis& axis = plot.Axes[i];

                // Create reference points on the interaction plane at range extremes
                ImPlot3DPoint p_min = mouse_pos_plot;
                ImPlot3DPoint p_max = mouse_pos_plot;
                p_min[i] = axis.Range.Min;
                p_max[i] = axis.Range.Max;

                // Transform to pixels
                ImVec2 pix_min = PlotToPixels(plot, p_min);
                ImVec2 pix_max = PlotToPixels(plot, p_max);

                // Compute the pixel distance from mouse to each endpoint
                ImVec2 mouse_pix = PlotToPixels(plot, mouse_pos_plot);
                float dist_min =
                    ImSqrt((pix_min.x - mouse_pix.x) * (pix_min.x - mouse_pix.x) + (pix_min.y - mouse_pix.y) * (pix_min.y - mouse_pix.y));
                float dist_max =
                    ImSqrt((pix_max.x - mouse_pix.x) * (pix_max.x - mouse_pix.x) + (pix_max.y - mouse_pix.y) * (pix_max.y - mouse_pix.y));

                if (zoom_around_mouse && (dist_min > 0 || dist_max > 0)) {
                    // Zoom around mouse: expand/contract distances from mouse position
                    // Direction vectors from mouse to endpoints
                    ImVec2 dir_min = pix_min - mouse_pix;
                    ImVec2 dir_max = pix_max - mouse_pix;

                    // Apply zoom by scaling the distances
                    // Note: zoom_rate is negative when zooming in (MouseWheel > 0), so we add it
                    pix_min = mouse_pix + dir_min * (1.0f + zoom_rate);
                    pix_max = mouse_pix + dir_max * (1.0f + zoom_rate);

                    // Project back to plot space via the plane
                    ImPlot3DPoint new_p_min = PixelsToPlotPlane(pix_min, mouse_plane, false);
                    ImPlot3DPoint new_p_max = PixelsToPlotPlane(pix_max, mouse_plane, false);

                    // Extract the new range for this axis
                    double new_min = new_p_min[i];
                    double new_max = new_p_max[i];

                    // Update the range
                    axis.SetRange(new_min, new_max);
                } else {
                    // Zoom around center
                    double ndc_limit = 0.5 * axis.NDCScale;
                    double zoom_factor = 1.0f + zoom_rate;

                    // Create points in NDC space representing the new zoomed range
                    ImPlot3DPoint ndc_min(0.0f, 0.0f, 0.0f);
                    ImPlot3DPoint ndc_max(0.0f, 0.0f, 0.0f);
                    ndc_min[i] = -ndc_limit * zoom_factor;
                    ndc_max[i] = ndc_limit * zoom_factor;

                    // Convert these NDC points to Plot space to get the new range
                    ImPlot3DPoint plt_min = NDCToPlot(ndc_min);
                    ImPlot3DPoint plt_max = NDCToPlot(ndc_max);

                    axis.SetRange(plt_min[i], plt_max[i]);
                }

                axis.Held = true;

                // Use a hovered axis as reference
                ref_axis = (ImAxis3D)i;
            }

            // Apply equal constraint using the reference axis
            if (axis_equal)
                plot.ApplyEqualAspect(ref_axis);

            // If no axis was held before (user started zoom in this frame), set the held edge/plane indices
            if (!any_axis_held) {
                plot.HeldEdgeIdx = hovered_edge_idx;
                plot.HeldPlaneIdx = hovered_plane_idx;
            }
        }
    }

    // CONTEXT MENU -------------------------------------------------------------------

    // Handle context click with right mouse button
    if (plot.Held && ImGui::IsMouseClicked(ImGuiMouseButton_Right) && !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoMenus))
        plot.ContextClick = true;
    if (rotating || (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right) && allow_rotate))
        plot.ContextClick = false;

    // Handle context menu (should not happen if it is not a double click action)
    bool not_double_click = allow_rotate ? (float)(ImGui::GetTime() - IO.MouseClickedTime[ImGuiMouseButton_Right]) > IO.MouseDoubleClickTime : true;
    if (plot.Hovered && plot.ContextClick && not_double_click && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) {
        plot.ContextClick = false;
        plot.OpenContextThisFrame = true;
    }

    if (plot.OpenContextThisFrame) {
        if (plot.Items.Legend.Hovered)
            ImGui::OpenPopup("##LegendContext");
        else if (hovered_axis != -1) {
            ImGui::OpenPopup(axis_contexts[hovered_axis]);
        } else if (hovered_plane != -1) {
            ImGui::OpenPopup(plane_contexts[hovered_plane]);
        } else if (plot.Hovered) {
            ImGui::OpenPopup("##PlotContext");
        }
    }
}

void SetupLock() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetupLock() needs to be called between BeginPlot() and EndPlot()!");
    ImPlot3DPlot& plot = *gp.CurrentPlot;
    if (plot.SetupLocked)
        return;
    // Lock setup
    plot.SetupLocked = true;

    ImGuiContext& g = *GImGui;
    ImGuiWindow* window = g.CurrentWindow;
    ImDrawList* draw_list = window->DrawList;

    // Set default formatter/locator
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];

        // Set formatter
        if (axis.Formatter == nullptr) {
            axis.Formatter = Formatter_Default;
            if (axis.FormatterData == nullptr)
                axis.FormatterData = (void*)IMPLOT3D_LABEL_FORMAT;
        }

        // Set locator
        if (axis.Locator == nullptr)
            axis.Locator = Locator_Default;
    }

    // Draw frame background
    ImU32 f_bg_color = GetStyleColorU32(ImPlot3DCol_FrameBg);
    draw_list->AddRectFilled(plot.FrameRect.Min, plot.FrameRect.Max, f_bg_color);

    // Compute canvas/canvas rectangle
    plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding);
    plot.PlotRect = plot.CanvasRect;

    // Apply equal axis aspect constraint if not approximately equal
    const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal);
    if (axis_equal) {
        double xar = plot.Axes[ImAxis3D_X].GetAspect();
        double yar = plot.Axes[ImAxis3D_Y].GetAspect();
        double zar = plot.Axes[ImAxis3D_Z].GetAspect();
        if (!ImAlmostEqual(xar, yar) || !ImAlmostEqual(xar, zar)) {
            double aspect = (xar + yar + zar) / 3.0;
            plot.Axes[ImAxis3D_X].SetAspect(aspect);
            plot.Axes[ImAxis3D_Y].SetAspect(aspect);
            plot.Axes[ImAxis3D_Z].SetAspect(aspect);
        }
    }

    // Compute ticks
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];
        if (axis.ShowDefaultTicks) {
            float pixels = float(plot.GetViewScale() * axis.NDCScale);
            axis.Locator(axis.Ticker, axis.Range, pixels, axis.Formatter, axis.FormatterData);
        }
    }

    // Cache axis colors
    for (int i = 0; i < 3; i++) {
        ImPlot3DAxis& axis = plot.Axes[i];
        axis.ColorBg = GetStyleColorU32(ImPlot3DCol_AxisBg);
        axis.ColorHov = GetStyleColorU32(ImPlot3DCol_AxisBgHovered);
        axis.ColorAct = GetStyleColorU32(ImPlot3DCol_AxisBgActive);
    }

    // Render title
    if (plot.HasTitle()) {
        ImU32 col = GetStyleColorU32(ImPlot3DCol_TitleText);
        ImVec2 top_center = ImVec2(plot.FrameRect.GetCenter().x, plot.CanvasRect.Min.y);
        AddTextCentered(draw_list, top_center, col, plot.GetTitle());
        plot.PlotRect.Min.y += ImGui::GetTextLineHeight() + gp.Style.LabelPadding.y;
    }

    // Handle animation
    if (plot.AnimationTime > 0.0f) {
        float dt = ImGui::GetIO().DeltaTime;
        float t = ImClamp(dt / plot.AnimationTime, 0.0f, 1.0f);
        plot.AnimationTime -= dt;
        if (plot.AnimationTime < 0.0f)
            plot.AnimationTime = 0.0f;
        plot.Rotation = ImPlot3DQuat::Slerp(plot.Rotation, plot.RotationAnimationEnd, t);
    }

    plot.Initialized = true;

    // Handle user input
    HandleInput(plot);

    // Push plot rect clipping
    ImGui::PushClipRect(plot.PlotRect.Min, plot.PlotRect.Max, true);

    // Render plot box
    RenderPlotBox(draw_list, plot);
}

//-----------------------------------------------------------------------------
// [SECTION] Miscellaneous
//-----------------------------------------------------------------------------

ImDrawList* GetPlotDrawList() { return ImGui::GetWindowDrawList(); }

//-----------------------------------------------------------------------------
// [SECTION] Styles
//-----------------------------------------------------------------------------

struct ImPlot3DStyleVarInfo {
    ImGuiDataType Type;
    ImU32 Count;
    ImU32 Offset;
    void* GetVarPtr(ImPlot3DStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};

static const ImPlot3DStyleVarInfo GPlot3DStyleVarInfo[] = {
    // Item style
    {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, LineWeight)}, // ImPlot3DStyleVar_LineWeight
    {ImGuiDataType_S32, 1, (ImU32)offsetof(ImPlot3DStyle, Marker)},       // ImPlot3DStyleVar_Marker
    {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerSize)}, // ImPlot3DStyleVar_MarkerSize
    {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, FillAlpha)},  // ImPlot3DStyleVar_FillAlpha

    // Plot style
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotDefaultSize)}, // ImPlot3DStyleVar_PlotDefaultSize
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotMinSize)},     // ImPlot3DStyleVar_PlotMinSize
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotPadding)},     // ImPlot3DStyleVar_PlotPadding
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LabelPadding)},    // ImPlot3DStyleVar_LabelPadding
    {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, ViewScaleFactor)}, // ImPlot3DStyleVar_ViewScaleFactor

    // Legend style
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendPadding)},      // ImPlot3DStyleVar_LegendPadding
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendInnerPadding)}, // ImPlot3DStyleVar_LegendInnerPadding
    {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendSpacing)},      // ImPlot3DStyleVar_LegendSpacing
};

static const ImPlot3DStyleVarInfo* GetPlotStyleVarInfo(ImPlot3DStyleVar idx) {
    IM_ASSERT(idx >= 0 && idx < ImPlot3DStyleVar_COUNT);
    IM_ASSERT(IM_ARRAYSIZE(GPlot3DStyleVarInfo) == ImPlot3DStyleVar_COUNT);
    return &GPlot3DStyleVarInfo[idx];
}

ImPlot3DStyle& GetStyle() { return GImPlot3D->Style; }
void SetStyle(const ImPlot3DStyle& style) { GImPlot3D->Style = style; }

void StyleColorsAuto(ImPlot3DStyle* dst) {
    ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
    ImVec4* colors = style->Colors;

    colors[ImPlot3DCol_TitleText] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_InlayText] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_FrameBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_PlotBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_PlotBorder] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_LegendBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_LegendBorder] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_LegendText] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisText] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisGrid] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL;
}

void StyleColorsDark(ImPlot3DStyle* dst) {
    ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
    ImVec4* colors = style->Colors;

    colors[ImPlot3DCol_TitleText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_InlayText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
    colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);
    colors[ImPlot3DCol_PlotBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
    colors[ImPlot3DCol_LegendBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
    colors[ImPlot3DCol_LegendBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
    colors[ImPlot3DCol_LegendText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_AxisText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f);
    colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL;
}

void StyleColorsLight(ImPlot3DStyle* dst) {
    ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
    ImVec4* colors = style->Colors;

    colors[ImPlot3DCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
    colors[ImPlot3DCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
    colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_PlotBg] = ImVec4(0.42f, 0.57f, 1.00f, 0.13f);
    colors[ImPlot3DCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
    colors[ImPlot3DCol_LegendBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
    colors[ImPlot3DCol_LegendBorder] = ImVec4(0.82f, 0.82f, 0.82f, 0.80f);
    colors[ImPlot3DCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
    colors[ImPlot3DCol_AxisText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
    colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
    colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL;
}

void StyleColorsClassic(ImPlot3DStyle* dst) {
    ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
    ImVec4* colors = style->Colors;

    colors[ImPlot3DCol_TitleText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
    colors[ImPlot3DCol_InlayText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
    colors[ImPlot3DCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
    colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.35f);
    colors[ImPlot3DCol_PlotBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
    colors[ImPlot3DCol_LegendBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
    colors[ImPlot3DCol_LegendBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
    colors[ImPlot3DCol_LegendText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
    colors[ImPlot3DCol_AxisText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
    colors[ImPlot3DCol_AxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f);
    colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL;
    colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL;
}

bool ShowStyleSelector(const char* label) {
    static int style_idx = -1;
    if (ImGui::Combo(label, &style_idx, "Auto\0Classic\0Dark\0Light\0")) {
        switch (style_idx) {
            case 0: StyleColorsAuto(); break;
            case 1: StyleColorsClassic(); break;
            case 2: StyleColorsDark(); break;
            case 3: StyleColorsLight(); break;
        }
        return true;
    }
    return false;
}

bool ShowColormapSelector(const char* label) {
    ImPlot3DContext& gp = *GImPlot3D;
    bool set = false;
    if (ImGui::BeginCombo(label, gp.ColormapData.GetName(gp.Style.Colormap))) {
        for (int i = 0; i < gp.ColormapData.Count; ++i) {
            const char* name = gp.ColormapData.GetName(i);
            if (ImGui::Selectable(name, gp.Style.Colormap == i)) {
                gp.Style.Colormap = i;
                BustItemCache();
                set = true;
            }
        }
        ImGui::EndCombo();
    }
    return set;
}

void PushStyleColor(ImPlot3DCol idx, ImU32 col) {
    ImPlot3DContext& gp = *GImPlot3D;
    ImGuiColorMod backup;
    backup.Col = (ImGuiCol)idx;
    backup.BackupValue = gp.Style.Colors[idx];
    gp.ColorModifiers.push_back(backup);
    gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col);
}

void PushStyleColor(ImPlot3DCol idx, const ImVec4& col) {
    ImPlot3DContext& gp = *GImPlot3D;
    ImGuiColorMod backup;
    backup.Col = (ImGuiCol)idx;
    backup.BackupValue = gp.Style.Colors[idx];
    gp.ColorModifiers.push_back(backup);
    gp.Style.Colors[idx] = col;
}

void PopStyleColor(int count) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, "You can't pop more modifiers than have been pushed!");
    while (count > 0) {
        ImGuiColorMod& backup = gp.ColorModifiers.back();
        gp.Style.Colors[backup.Col] = backup.BackupValue;
        gp.ColorModifiers.pop_back();
        count--;
    }
}

void PushStyleVar(ImPlot3DStyleVar idx, float val) {
    ImPlot3DContext& gp = *GImPlot3D;
    const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
        float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
        gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
        *pvar = val;
        return;
    }
    IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}

void PushStyleVar(ImPlot3DStyleVar idx, int val) {
    ImPlot3DContext& gp = *GImPlot3D;
    const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
    if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) {
        int* pvar = (int*)var_info->GetVarPtr(&gp.Style);
        gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
        *pvar = val;
        return;
    } else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
        float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
        gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
        *pvar = (float)val;
        return;
    }
    IM_ASSERT(0 && "Called PushStyleVar() int variant but variable is not a int!");
}

void PushStyleVar(ImPlot3DStyleVar idx, const ImVec2& val) {
    ImPlot3DContext& gp = *GImPlot3D;
    const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) {
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style);
        gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
        *pvar = val;
        return;
    }
    IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}

void PopStyleVar(int count) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, "You can't pop more modifiers than have been pushed!");
    while (count > 0) {
        ImGuiStyleMod& backup = gp.StyleModifiers.back();
        const ImPlot3DStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx);
        void* data = info->GetVarPtr(&gp.Style);
        if (info->Type == ImGuiDataType_Float && info->Count == 1) {
            ((float*)data)[0] = backup.BackupFloat[0];
        } else if (info->Type == ImGuiDataType_Float && info->Count == 2) {
            ((float*)data)[0] = backup.BackupFloat[0];
            ((float*)data)[1] = backup.BackupFloat[1];
        } else if (info->Type == ImGuiDataType_S32 && info->Count == 1) {
            ((int*)data)[0] = backup.BackupInt[0];
        }
        gp.StyleModifiers.pop_back();
        count--;
    }
}

ImVec4 GetStyleColorVec4(ImPlot3DCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot3D->Style.Colors[idx]; }

ImU32 GetStyleColorU32(ImPlot3DCol idx) { return ImGui::ColorConvertFloat4ToU32(ImPlot3D::GetStyleColorVec4(idx)); }

ImPlot3DMarker NextMarker() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextMarker() needs to be called between BeginPlot() and EndPlot()!");
    const int idx = gp.CurrentItems->MarkerIdx % ImPlot3DMarker_COUNT;
    ++gp.CurrentItems->MarkerIdx;
    return idx;
}

//------------------------------------------------------------------------------
// [SECTION] Colormaps
//------------------------------------------------------------------------------

ImPlot3DColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
    IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!");
    ImVector<ImU32> buffer;
    buffer.resize(size);
    for (int i = 0; i < size; i++)
        buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]);
    return gp.ColormapData.Append(name, buffer.Data, size, qual);
}

ImPlot3DColormap AddColormap(const char* name, const ImU32* colormap, int size, bool qual) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
    IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already be used!");
    return gp.ColormapData.Append(name, colormap, size, qual);
}

int GetColormapCount() {
    ImPlot3DContext& gp = *GImPlot3D;
    return gp.ColormapData.Count;
}

const char* GetColormapName(ImPlot3DColormap colormap) {
    ImPlot3DContext& gp = *GImPlot3D;
    return gp.ColormapData.GetName(colormap);
}

ImPlot3DColormap GetColormapIndex(const char* name) {
    ImPlot3DContext& gp = *GImPlot3D;
    return gp.ColormapData.GetIndex(name);
}

void PushColormap(ImPlot3DColormap colormap) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, "The colormap index is invalid!");
    gp.ColormapModifiers.push_back(gp.Style.Colormap);
    gp.Style.Colormap = colormap;
}

void PushColormap(const char* name) {
    ImPlot3DContext& gp = *GImPlot3D;
    ImPlot3DColormap idx = gp.ColormapData.GetIndex(name);
    IM_ASSERT_USER_ERROR(idx != -1, "The colormap name is invalid!");
    PushColormap(idx);
}

void PopColormap(int count) {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, "You can't pop more modifiers than have been pushed!");
    while (count > 0) {
        const ImPlot3DColormap& backup = gp.ColormapModifiers.back();
        gp.Style.Colormap = backup;
        gp.ColormapModifiers.pop_back();
        count--;
    }
}

ImU32 NextColormapColorU32() {
    ImPlot3DContext& gp = *GImPlot3D;
    IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!");
    int idx = gp.CurrentItems->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap);
    ImU32 col = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx);
    gp.CurrentItems->ColormapIdx++;
    return col;
}

ImVec4 NextColormapColor() { return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32()); }

int GetColormapSize(ImPlot3DColormap cmap) {
    ImPlot3DContext& gp = *GImPlot3D;
    cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
    return gp.ColormapData.GetKeyCount(cmap);
}

ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap) {
    ImPlot3DContext& gp = *GImPlot3D;
    cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
    idx = idx % gp.ColormapData.GetKeyCount(cmap);
    return gp.ColormapData.GetKeyColor(cmap, idx);
}

ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx, cmap)); }

ImU32 SampleColormapU32(float t, ImPlot3DColormap cmap) {
    ImPlot3DContext& gp = *GImPlot3D;
    cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
    return gp.ColormapData.LerpTable(cmap, t);
}

ImVec4 SampleColormap(float t, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t, cmap)); }

void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) {
    const int n = continuous ? size - 1 : size;
    ImU32 col1, col2;
    if (vert) {
        const float step = bounds.GetHeight() / n;
        ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step);
        for (int i = 0; i < n; ++i) {
            if (reversed) {
                col1 = colors[size - i - 1];
                col2 = continuous ? colors[size - i - 2] : col1;
            } else {
                col1 = colors[i];
                col2 = continuous ? colors[i + 1] : col1;
            }
            DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2);
            rect.TranslateY(step);
        }
    } else {
        const float step = bounds.GetWidth() / n;
        ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y);
        for (int i = 0; i < n; ++i) {
            if (reversed) {
                col1 = colors[size - i - 1];
                col2 = continuous ? colors[size - i - 2] : col1;
            } else {
                col1 = colors[i];
                col2 = continuous ? colors[i + 1] : col1;
            }
            DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1);
            rect.TranslateX(step);
        }
    }
}

bool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlot3DColormap cmap) {
    *t = ImClamp(*t, 0.0f, 1.0f);
    ImGuiContext& G = *GImGui;
    ImGuiWindow* Window = G.CurrentWindow;
    if (Window->SkipItems)
        return false;
    ImPlot3DContext& gp = *GImPlot3D;
    cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
    const ImU32* keys = gp.ColormapData.GetKeys(cmap);
    const int count = gp.ColormapData.GetKeyCount(cmap);
    const bool qual = gp.ColormapData.IsQual(cmap);
    const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos;
    const float w = ImGui::CalcItemWidth();
    const float h = ImGui::GetFrameHeight();
    const ImRect rect = ImRect(pos.x, pos.y, pos.x + w, pos.y + h);
    RenderColorBar(keys, count, *ImGui::GetWindowDrawList(), rect, false, false, !qual);
    const ImU32 grab = CalcTextColor(gp.ColormapData.LerpTable(cmap, *t));
    // const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap,0.5f));
    ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32_BLACK_TRANS);
    ImGui::PushStyleColor(ImGuiCol_FrameBgActive, IM_COL32_BLACK_TRANS);
    ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(1, 1, 1, 0.1f));
    ImGui::PushStyleColor(ImGuiCol_SliderGrab, grab);
    ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab);
    ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 2);
    ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);
    const bool changed = ImGui::SliderFloat(label, t, 0, 1, format);
    ImGui::PopStyleColor(5);
    ImGui::PopStyleVar(2);
    if (out != nullptr)
        *out = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.LerpTable(cmap, *t));
    return changed;
}

//-----------------------------------------------------------------------------
// [SECTION] Context Utils
//-----------------------------------------------------------------------------

#define IMPLOT3D_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name) / sizeof(ImU32), qual)
#define IM_RGB(r, g, b) IM_COL32(r, g, b, 255)

void InitializeContext(ImPlot3DContext* ctx) {
    ResetContext(ctx);

    const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396};
    const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409};
    const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986};
    const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971,
                            4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481};
    const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273,
                             4286883874, 4285579076, 4283552122, 4280737725, 4280674301};
    const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780,
                            4284638433, 4283139314, 4281771772, 4280667900, 4280416752};
    const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103,
                         4278239231, 4278255615, 4283826175, 4289396735, 4294967295};
    const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656,
                          4294928025, 4294921651, 4294915020, 4294908646, 4294902015};
    const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160,
                          4288794330, 4289651940, 4291685869, 4293392118, 4294967295};
    const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565,
                         4283826090, 4278255615, 4278233855, 4278212095, 4278190335};
    const ImU32 Twilight[] = {IM_RGB(226, 217, 226), IM_RGB(166, 191, 202), IM_RGB(109, 144, 192), IM_RGB(95, 88, 176),
                              IM_RGB(83, 30, 124),   IM_RGB(47, 20, 54),    IM_RGB(100, 25, 75),   IM_RGB(159, 60, 80),
                              IM_RGB(192, 117, 94),  IM_RGB(208, 179, 158), IM_RGB(226, 217, 226)};
    const ImU32 RdBu[] = {IM_RGB(103, 0, 31),    IM_RGB(178, 24, 43),   IM_RGB(214, 96, 77),   IM_RGB(244, 165, 130),
                          IM_RGB(253, 219, 199), IM_RGB(247, 247, 247), IM_RGB(209, 229, 240), IM_RGB(146, 197, 222),
                          IM_RGB(67, 147, 195),  IM_RGB(33, 102, 172),  IM_RGB(5, 48, 97)};
    const ImU32 BrBG[] = {IM_RGB(84, 48, 5),     IM_RGB(140, 81, 10),   IM_RGB(191, 129, 45),  IM_RGB(223, 194, 125),
                          IM_RGB(246, 232, 195), IM_RGB(245, 245, 245), IM_RGB(199, 234, 229), IM_RGB(128, 205, 193),
                          IM_RGB(53, 151, 143),  IM_RGB(1, 102, 94),    IM_RGB(0, 60, 48)};
    const ImU32 PiYG[] = {IM_RGB(142, 1, 82),    IM_RGB(197, 27, 125),  IM_RGB(222, 119, 174), IM_RGB(241, 182, 218),
                          IM_RGB(253, 224, 239), IM_RGB(247, 247, 247), IM_RGB(230, 245, 208), IM_RGB(184, 225, 134),
                          IM_RGB(127, 188, 65),  IM_RGB(77, 146, 33),   IM_RGB(39, 100, 25)};
    const ImU32 Spectral[] = {IM_RGB(158, 1, 66),    IM_RGB(213, 62, 79),   IM_RGB(244, 109, 67),  IM_RGB(253, 174, 97),
                              IM_RGB(254, 224, 139), IM_RGB(255, 255, 191), IM_RGB(230, 245, 152), IM_RGB(171, 221, 164),
                              IM_RGB(102, 194, 165), IM_RGB(50, 136, 189),  IM_RGB(94, 79, 162)};
    const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK};

    IMPLOT3D_APPEND_CMAP(Deep, true);
    IMPLOT3D_APPEND_CMAP(Dark, true);
    IMPLOT3D_APPEND_CMAP(Pastel, true);
    IMPLOT3D_APPEND_CMAP(Paired, true);
    IMPLOT3D_APPEND_CMAP(Viridis, false);
    IMPLOT3D_APPEND_CMAP(Plasma, false);
    IMPLOT3D_APPEND_CMAP(Hot, false);
    IMPLOT3D_APPEND_CMAP(Cool, false);
    IMPLOT3D_APPEND_CMAP(Pink, false);
    IMPLOT3D_APPEND_CMAP(Jet, false);
    IMPLOT3D_APPEND_CMAP(Twilight, false);
    IMPLOT3D_APPEND_CMAP(RdBu, false);
    IMPLOT3D_APPEND_CMAP(BrBG, false);
    IMPLOT3D_APPEND_CMAP(PiYG, false);
    IMPLOT3D_APPEND_CMAP(Spectral, false);
    IMPLOT3D_APPEND_CMAP(Greys, false);
}

void ResetContext(ImPlot3DContext* ctx) {
    ctx->Plots.Clear();
    ctx->CurrentPlot = nullptr;
    ctx->CurrentItems = nullptr;
    ctx->CurrentItem = nullptr;
    ctx->NextItemData.Reset();
    ctx->Style = ImPlot3DStyle();
}

//-----------------------------------------------------------------------------
// [SECTION] Style Utils
//-----------------------------------------------------------------------------

bool IsColorAuto(const ImVec4& col) { return col.w == -1.0f; }

bool IsColorAuto(ImPlot3DCol idx) { return IsColorAuto(GImPlot3D->Style.Colors[idx]); }

ImVec4 GetAutoColor(ImPlot3DCol idx) {
    switch (idx) {
        case ImPlot3DCol_TitleText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlot3DCol_InlayText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlot3DCol_FrameBg: return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);
        case ImPlot3DCol_PlotBg: return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
        case ImPlot3DCol_PlotBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border);
        case ImPlot3DCol_LegendBg: return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg);
        case ImPlot3DCol_LegendBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border);
        case ImPlot3DCol_LegendText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlot3DCol_AxisText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlot3DCol_AxisGrid: return ImGui::GetStyleColorVec4(ImGuiCol_Text) * ImVec4(1, 1, 1, 0.25f);
        case ImPlot3DCol_AxisTick: return GetStyleColorVec4(ImPlot3DCol_AxisGrid);
        case ImPlot3DCol_AxisBg: return ImVec4(0, 0, 0, 0);
        case ImPlot3DCol_AxisBgHovered: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered);
        case ImPlot3DCol_AxisBgActive: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive);
        default: return IMPLOT3D_AUTO_COL;
    }
}

const char* GetStyleColorName(ImPlot3DCol idx) {
    static const char* color_names[ImPlot3DCol_COUNT] = {
        "TitleText",  "InlayText", "FrameBg",  "PlotBg",   "PlotBorder", "LegendBg",      "LegendBorder",
        "LegendText", "AxisText",  "AxisGrid", "AxisTick", "AxisBg",     "AxisBgHovered", "AxisBgActive",
    };
    return color_names[idx];
}

const ImPlot3DNextItemData& GetItemData() { return GImPlot3D->NextItemData; }

} // namespace ImPlot3D

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DPoint
//-----------------------------------------------------------------------------

ImPlot3DPoint ImPlot3DPoint::operator*(double rhs) const { return ImPlot3DPoint(x * rhs, y * rhs, z * rhs); }
ImPlot3DPoint ImPlot3DPoint::operator/(double rhs) const { return ImPlot3DPoint(x / rhs, y / rhs, z / rhs); }
ImPlot3DPoint ImPlot3DPoint::operator+(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x + rhs.x, y + rhs.y, z + rhs.z); }
ImPlot3DPoint ImPlot3DPoint::operator-(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x - rhs.x, y - rhs.y, z - rhs.z); }
ImPlot3DPoint ImPlot3DPoint::operator*(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x * rhs.x, y * rhs.y, z * rhs.z); }
ImPlot3DPoint ImPlot3DPoint::operator/(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x / rhs.x, y / rhs.y, z / rhs.z); }
ImPlot3DPoint ImPlot3DPoint::operator-() const { return ImPlot3DPoint(-x, -y, -z); }

ImPlot3DPoint& ImPlot3DPoint::operator*=(double rhs) {
    x *= rhs;
    y *= rhs;
    z *= rhs;
    return *this;
}
ImPlot3DPoint& ImPlot3DPoint::operator/=(double rhs) {
    x /= rhs;
    y /= rhs;
    z /= rhs;
    return *this;
}
ImPlot3DPoint& ImPlot3DPoint::operator+=(const ImPlot3DPoint& rhs) {
    x += rhs.x;
    y += rhs.y;
    z += rhs.z;
    return *this;
}
ImPlot3DPoint& ImPlot3DPoint::operator-=(const ImPlot3DPoint& rhs) {
    x -= rhs.x;
    y -= rhs.y;
    z -= rhs.z;
    return *this;
}
ImPlot3DPoint& ImPlot3DPoint::operator*=(const ImPlot3DPoint& rhs) {
    x *= rhs.x;
    y *= rhs.y;
    z *= rhs.z;
    return *this;
}
ImPlot3DPoint& ImPlot3DPoint::operator/=(const ImPlot3DPoint& rhs) {
    x /= rhs.x;
    y /= rhs.y;
    z /= rhs.z;
    return *this;
}

bool ImPlot3DPoint::operator==(const ImPlot3DPoint& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; }
bool ImPlot3DPoint::operator!=(const ImPlot3DPoint& rhs) const { return !(*this == rhs); }

double ImPlot3DPoint::Dot(const ImPlot3DPoint& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }

ImPlot3DPoint ImPlot3DPoint::Cross(const ImPlot3DPoint& rhs) const {
    return ImPlot3DPoint(y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x);
}

double ImPlot3DPoint::Length() const { return sqrt(x * x + y * y + z * z); }

double ImPlot3DPoint::LengthSquared() const { return x * x + y * y + z * z; }

void ImPlot3DPoint::Normalize() {
    double l = Length();
    x /= l;
    y /= l;
    z /= l;
}

ImPlot3DPoint ImPlot3DPoint::Normalized() const {
    double l = Length();
    return ImPlot3DPoint(x / l, y / l, z / l);
}

ImPlot3DPoint operator*(double lhs, const ImPlot3DPoint& rhs) { return ImPlot3DPoint(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); }

bool ImPlot3DPoint::IsNaN() const { return ImPlot3D::ImNan(x) || ImPlot3D::ImNan(y) || ImPlot3D::ImNan(z); }

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DBox
//-----------------------------------------------------------------------------

void ImPlot3DBox::Expand(const ImPlot3DPoint& point) {
    Min.x = ImMin(Min.x, point.x);
    Min.y = ImMin(Min.y, point.y);
    Min.z = ImMin(Min.z, point.z);
    Max.x = ImMax(Max.x, point.x);
    Max.y = ImMax(Max.y, point.y);
    Max.z = ImMax(Max.z, point.z);
}

bool ImPlot3DBox::Contains(const ImPlot3DPoint& point) const {
    return (point.x >= Min.x && point.x <= Max.x) && (point.y >= Min.y && point.y <= Max.y) && (point.z >= Min.z && point.z <= Max.z);
}

bool ImPlot3DBox::ClipLineSegment(const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, ImPlot3DPoint& p0_clipped, ImPlot3DPoint& p1_clipped) const {
    // Check if the line segment is completely inside the box
    if (Contains(p0) && Contains(p1)) {
        p0_clipped = p0;
        p1_clipped = p1;
        return true;
    }

    // Perform Liang-Barsky 3D clipping
    double t0 = 0.0;
    double t1 = 1.0;
    ImPlot3DPoint d = p1 - p0;

    // Define the clipping boundaries
    const double xmin = Min.x, xmax = Max.x;
    const double ymin = Min.y, ymax = Max.y;
    const double zmin = Min.z, zmax = Max.z;

    // Lambda function to update t0 and t1
    auto update = [&](double p, double q) -> bool {
        if (p == 0.0) {
            if (q < 0.0)
                return false; // Line is parallel and outside the boundary
            else
                return true; // Line is parallel and inside or coincident with boundary
        }
        double r = q / p;
        if (p < 0.0) {
            if (r > t1)
                return false; // Line is outside
            if (r > t0)
                t0 = r; // Move up t0
        } else {
            if (r < t0)
                return false; // Line is outside
            if (r < t1)
                t1 = r; // Move down t1
        }
        return true;
    };

    // Clip against each boundary
    if (!update(-d.x, p0.x - xmin))
        return false; // Left
    if (!update(d.x, xmax - p0.x))
        return false; // Right
    if (!update(-d.y, p0.y - ymin))
        return false; // Bottom
    if (!update(d.y, ymax - p0.y))
        return false; // Top
    if (!update(-d.z, p0.z - zmin))
        return false; // Near
    if (!update(d.z, zmax - p0.z))
        return false; // Far

    // Compute clipped points
    p0_clipped = p0 + d * t0;
    p1_clipped = p0 + d * t1;

    return true;
}

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DRange
//-----------------------------------------------------------------------------

void ImPlot3DRange::Expand(double value) {
    Min = ImMin(Min, value);
    Max = ImMax(Max, value);
}

bool ImPlot3DRange::Contains(double value) const { return value >= Min && value <= Max; }

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DQuat
//-----------------------------------------------------------------------------

ImPlot3DQuat::ImPlot3DQuat(double _angle, const ImPlot3DPoint& _axis) {
    double half_angle = _angle * 0.5;
    double s = sin(half_angle);
    x = s * _axis.x;
    y = s * _axis.y;
    z = s * _axis.z;
    w = cos(half_angle);
}

ImPlot3DQuat ImPlot3DQuat::FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3DPoint& v1) {
    ImPlot3DQuat q;

    // Compute the dot product and lengths of the vectors
    double dot = v0.Dot(v1);
    double length_v0 = v0.Length();
    double length_v1 = v1.Length();

    // Normalize the dot product
    double normalized_dot = dot / (length_v0 * length_v1);

    // Handle edge cases: if vectors are very close or identical
    const double epsilon = 1e-6;
    if (ImAbs(normalized_dot - 1.0) < epsilon) {
        // v0 and v1 are nearly identical; return an identity quaternion
        q.x = 0.0;
        q.y = 0.0;
        q.z = 0.0;
        q.w = 1.0;
        return q;
    }

    // Handle edge case: if vectors are opposite
    if (ImAbs(normalized_dot + 1.0) < epsilon) {
        // v0 and v1 are opposite; choose an arbitrary orthogonal axis
        ImPlot3DPoint arbitrary_axis = ImAbs(v0.x) > ImAbs(v0.z) ? ImPlot3DPoint(-v0.y, v0.x, 0.0) : ImPlot3DPoint(0.0, -v0.z, v0.y);
        arbitrary_axis.Normalize();
        q.x = arbitrary_axis.x;
        q.y = arbitrary_axis.y;
        q.z = arbitrary_axis.z;
        q.w = 0.0;
        return q;
    }

    // General case
    ImPlot3DPoint axis = v0.Cross(v1);
    axis.Normalize();
    double angle = acos(normalized_dot);
    double half_angle = angle * 0.5;
    double s = sin(half_angle);
    q.x = s * axis.x;
    q.y = s * axis.y;
    q.z = s * axis.z;
    q.w = cos(half_angle);

    return q;
}

ImPlot3DQuat ImPlot3DQuat::FromElAz(double elevation, double azimuth) {
    // Create quaternions for azimuth and elevation
    ImPlot3DQuat azimuth_quat(azimuth, ImPlot3DPoint(0.0, 0.0, 1.0));     // Rotate around Z-axis
    ImPlot3DQuat elevation_quat(elevation, ImPlot3DPoint(1.0, 0.0, 0.0)); // Rotate around X-axis
    ImPlot3DQuat zero_quat(-IM_PI / 2, ImPlot3DPoint(1.0, 0.0, 0.0));     // Rotate to zero azimuth/elevation orientation

    // Combine rotations
    return elevation_quat * zero_quat * azimuth_quat;
}

double ImPlot3DQuat::Length() const { return sqrt(x * x + y * y + z * z + w * w); }

ImPlot3DQuat ImPlot3DQuat::Normalized() const {
    double l = Length();
    return ImPlot3DQuat(x / l, y / l, z / l, w / l);
}

ImPlot3DQuat ImPlot3DQuat::Conjugate() const { return ImPlot3DQuat(-x, -y, -z, w); }

ImPlot3DQuat ImPlot3DQuat::Inverse() const {
    double l_squared = x * x + y * y + z * z + w * w;
    return ImPlot3DQuat(-x / l_squared, -y / l_squared, -z / l_squared, w / l_squared);
}

ImPlot3DQuat ImPlot3DQuat::operator*(const ImPlot3DQuat& rhs) const {
    return ImPlot3DQuat(w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y, w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x,
                        w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w, w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z);
}

ImPlot3DQuat& ImPlot3DQuat::Normalize() {
    double l = Length();
    x /= l;
    y /= l;
    z /= l;
    w /= l;
    return *this;
}

ImPlot3DPoint ImPlot3DQuat::operator*(const ImPlot3DPoint& point) const {
    // Extract vector part of the quaternion
    ImPlot3DPoint qv(x, y, z);

    // Compute the cross products needed for rotation
    ImPlot3DPoint uv = qv.Cross(point); // uv = qv x point
    ImPlot3DPoint uuv = qv.Cross(uv);   // uuv = qv x uv

    // Compute the rotated vector
    return point + (uv * w * 2.0) + (uuv * 2.0);
}

bool ImPlot3DQuat::operator==(const ImPlot3DQuat& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; }

bool ImPlot3DQuat::operator!=(const ImPlot3DQuat& rhs) const { return !(*this == rhs); }

ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, double t) {
    // Clamp t to [0, 1]
    t = ImClamp(t, 0.0, 1.0);

    // Compute the dot product (cosine of the angle between quaternions)
    double dot = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;

    // If the dot product is negative, negate one quaternion to take the shorter path
    ImPlot3DQuat q2_ = q2;
    if (dot < 0.0) {
        q2_ = ImPlot3DQuat(-q2.x, -q2.y, -q2.z, -q2.w);
        dot = -dot;
    }

    // If the quaternions are very close, use linear interpolation to avoid numerical instability
    if (dot > 0.9995) {
        return ImPlot3DQuat(q1.x + t * (q2_.x - q1.x), q1.y + t * (q2_.y - q1.y), q1.z + t * (q2_.z - q1.z), q1.w + t * (q2_.w - q1.w)).Normalized();
    }

    // Compute the angle and the interpolation factors
    double theta_0 = acos(dot);        // Angle between input quaternions
    double theta = theta_0 * t;        // Interpolated angle
    double sin_theta = sin(theta);     // Sine of interpolated angle
    double sin_theta_0 = sin(theta_0); // Sine of original angle

    double s1 = cos(theta) - dot * sin_theta / sin_theta_0;
    double s2 = sin_theta / sin_theta_0;

    // Interpolate and return the result
    return ImPlot3DQuat(s1 * q1.x + s2 * q2_.x, s1 * q1.y + s2 * q2_.y, s1 * q1.z + s2 * q2_.z, s1 * q1.w + s2 * q2_.w);
}

double ImPlot3DQuat::Dot(const ImPlot3DQuat& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w; }

//-----------------------------------------------------------------------------
// [SECTION] ImDrawList3D
//-----------------------------------------------------------------------------

void ImDrawList3D::PrimReserve(int idx_count, int vtx_count) {
    IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0);

    int vtx_buffer_old_size = VtxBuffer.Size;
    VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
    _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;

    int idx_buffer_old_size = IdxBuffer.Size;
    IdxBuffer.resize(idx_buffer_old_size + idx_count);
    _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;

    int z_buffer_old_size = ZBuffer.Size;
    ZBuffer.resize(z_buffer_old_size + idx_count / 3);
    _ZWritePtr = ZBuffer.Data + z_buffer_old_size;
}

void ImDrawList3D::PrimUnreserve(int idx_count, int vtx_count) {
    IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0);

    VtxBuffer.shrink(VtxBuffer.Size - vtx_count);
    IdxBuffer.shrink(IdxBuffer.Size - idx_count);
    ZBuffer.shrink(ZBuffer.Size - idx_count / 3);
}

void ImDrawList3D::SetTexture(ImTextureRef tex_ref) {
    if (_TextureBuffer.empty()) {
        // First texture assignment
        _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx});
        return;
    }

    ImTextureBufferItem& prev_item = _TextureBuffer.back();
    if (prev_item.VtxIdx == _VtxCurrentIdx) {
        // Same vertex index: update existing texture ID
        prev_item.TexRef = tex_ref;

        // If the previous texture was the same, remove current texture
        if (_TextureBuffer.Size >= 2) {
            if (_TextureBuffer[_TextureBuffer.Size - 2].TexRef == tex_ref) {
                _TextureBuffer.pop_back();
            }
        }
    } else if (prev_item.TexRef != tex_ref) {
        // New vertex index and different texture: insert new item
        _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx});
    }
}

void ImDrawList3D::ResetTexture() { SetTexture(ImTextureID(0)); }

#ifdef IMGUI_HAS_TEXTURES
#define SET_TEX_REF(cmd, tex_ref) (cmd).TexRef = (tex_ref)
#define GET_TEX_REF(cmd) (cmd).TexRef
#else
#define SET_TEX_REF(cmd, tex_ref) (cmd).TextureId = (tex_ref)
#define GET_TEX_REF(cmd) (cmd).TextureId
#endif

void ImDrawList3D::SortedMoveToImGuiDrawList() {
    ImDrawList& draw_list = *ImGui::GetWindowDrawList();

    const int tri_count = ZBuffer.Size;
    if (tri_count == 0) {
        // No triangles, just reset buffers and return
        ResetBuffers();
        return;
    }

    // Build an array of (z, tri_idx)
    struct TriRef {
        double z;
        int tri_idx;
    };
    TriRef* tris = (TriRef*)IM_ALLOC(sizeof(TriRef) * tri_count);
    for (int i = 0; i < tri_count; i++) {
        tris[i].z = ZBuffer[i];
        tris[i].tri_idx = i;
    }

    // Sort by z (distance from viewer)
    ImQsort(tris, (size_t)tri_count, sizeof(TriRef), [](const void* a, const void* b) {
        double za = ((const TriRef*)a)->z;
        double zb = ((const TriRef*)b)->z;
        return (za < zb) ? -1 : (za > zb) ? 1 : 0;
    });

    // Reserve space in the ImGui draw list
    draw_list.PrimReserve(IdxBuffer.Size, VtxBuffer.Size);

    // Copy vertices (no reordering needed)
    memcpy(draw_list._VtxWritePtr, VtxBuffer.Data, VtxBuffer.Size * sizeof(ImDrawVert));
    unsigned int idx_offset = draw_list._VtxCurrentIdx;
    draw_list._VtxWritePtr += VtxBuffer.Size;
    draw_list._VtxCurrentIdx += (unsigned int)VtxBuffer.Size;

    // Maximum index allowed to not overflow ImDrawIdx
    unsigned int max_index_allowed = MaxIdx() - idx_offset;

    // Copy indices with triangle sorting based on distance from viewer
    ImDrawIdx* idx_out_begin = draw_list._IdxWritePtr;
    ImDrawIdx* idx_out = idx_out_begin;
    ImDrawIdx* idx_in = IdxBuffer.Data;
    for (int i = 0; i < tri_count; i++) {
        int tri_i = tris[i].tri_idx;
        int base_idx = tri_i * 3;
        unsigned int i0 = (unsigned int)idx_in[base_idx + 0];
        unsigned int i1 = (unsigned int)idx_in[base_idx + 1];
        unsigned int i2 = (unsigned int)idx_in[base_idx + 2];

        // Check if after adding offset any of these indices exceed max_index_allowed
        if (i0 > max_index_allowed || i1 > max_index_allowed || i2 > max_index_allowed)
            continue;

        idx_out[0] = (ImDrawIdx)(i0 + idx_offset);
        idx_out[1] = (ImDrawIdx)(i1 + idx_offset);
        idx_out[2] = (ImDrawIdx)(i2 + idx_offset);

        idx_out += 3;
    }
    ImDrawIdx* idx_out_end = idx_out;
    draw_list._IdxWritePtr = idx_out_end;

    // If multiple textures were used (e.g. PlotImage was called), generate multiple ImDrawCmd
    if (_TextureBuffer.Size > 1) {
        ImTextureRef default_tex = GET_TEX_REF(draw_list._CmdHeader);
        ImTextureRef curr_tex = default_tex;

        // Remove elements reserved from PrimReserve
        draw_list.CmdBuffer.back().ElemCount -= IdxBuffer.Size;
        ImDrawIdx* last_cmd_buffer_idx = idx_out_begin;

        // For each triangle added to the draw_list
        for (idx_out = idx_out_begin; idx_out < idx_out_end; idx_out += 3) {
            // Get index of first vertex in the triangle
            unsigned int vtx_idx = (unsigned int)(*idx_out - idx_offset);

            // Get the texture for this triangle
            const ImTextureRef invalid_tex = ImTextureID(0);
            ImTextureRef tri_tex = invalid_tex;
            for (int j = 0; j < _TextureBuffer.Size; j++)
                if (vtx_idx >= _TextureBuffer[j].VtxIdx)
                    tri_tex = _TextureBuffer[j].TexRef;

            // If tri_tex is invalid, the default texture should be used
            if (tri_tex == invalid_tex)
                tri_tex = default_tex;

            if (tri_tex != curr_tex) {
                // Update element count of previous draw cmd
                draw_list.CmdBuffer.back().ElemCount += (unsigned int)(idx_out - last_cmd_buffer_idx);
                last_cmd_buffer_idx = idx_out;

                // Set custom texture
                curr_tex = tri_tex;
                SET_TEX_REF(draw_list._CmdHeader, curr_tex);

                // Add new draw cmd for the new texture
                ImDrawCmd draw_cmd;
                draw_cmd.ClipRect = draw_list._CmdHeader.ClipRect;
                SET_TEX_REF(draw_cmd, GET_TEX_REF(draw_list._CmdHeader));
                draw_cmd.VtxOffset = draw_list._CmdHeader.VtxOffset;
                draw_cmd.IdxOffset = (unsigned int)(idx_out - draw_list.IdxBuffer.Data);
                draw_list.CmdBuffer.push_back(draw_cmd);
            }
        }
        // Flush last elements to cmd buffer
        draw_list.CmdBuffer.back().ElemCount += (unsigned int)(&draw_list.IdxBuffer.back() - last_cmd_buffer_idx + 1);

        // Check if the last texture was not the default texture
        if (curr_tex != default_tex) {
            // Restore default texture
            SET_TEX_REF(draw_list._CmdHeader, default_tex);

            // Flush last draw cmd with custom texture
            draw_list.AddDrawCmd();
        }
    }

    // Reset buffers since we've moved them
    ResetBuffers();

    IM_FREE(tris);
}

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DAxis
//-----------------------------------------------------------------------------

bool ImPlot3DAxis::HasLabel() const { return !Label.empty() && !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoLabel); }
bool ImPlot3DAxis::HasGridLines() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoGridLines); }
bool ImPlot3DAxis::HasTickLabels() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickLabels); }
bool ImPlot3DAxis::HasTickMarks() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickMarks); }
bool ImPlot3DAxis::IsAutoFitting() const { return ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_AutoFit); }

void ImPlot3DAxis::ExtendFit(double value) {
    // Only extend fit with values that are within the constraint range
    // This is critical for log scale where negative/zero values should be ignored
    if (!ImPlot3D::ImNanOrInf(value) && value >= ConstraintRange.Min && value <= ConstraintRange.Max) {
        FitExtents.Min = ImMin(FitExtents.Min, value);
        FitExtents.Max = ImMax(FitExtents.Max, value);
    }
}

void ImPlot3DAxis::ApplyFit() {
    if (!IsLockedMin() && !ImPlot3D::ImNanOrInf(FitExtents.Min))
        Range.Min = FitExtents.Min;
    if (!IsLockedMax() && !ImPlot3D::ImNanOrInf(FitExtents.Max))
        Range.Max = FitExtents.Max;
    if (ImPlot3D::ImAlmostEqual(Range.Min, Range.Max)) {
        Range.Max += 0.5;
        Range.Min -= 0.5;
    }
    Constrain();
    UpdateTransformCache();
    FitExtents.Min = HUGE_VAL;
    FitExtents.Max = -HUGE_VAL;
}

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DPlot
//-----------------------------------------------------------------------------

void ImPlot3DPlot::ExtendFit(const ImPlot3DPoint& point) {
    for (int i = 0; i < 3; i++) {
        if (!ImPlot3D::ImNanOrInf(point[i]) && Axes[i].FitThisFrame)
            Axes[i].ExtendFit(point[i]);
    }
}

ImPlot3DPoint ImPlot3DPlot::RangeMin() const { return ImPlot3DPoint(Axes[0].Range.Min, Axes[1].Range.Min, Axes[2].Range.Min); }

ImPlot3DPoint ImPlot3DPlot::RangeMax() const { return ImPlot3DPoint(Axes[0].Range.Max, Axes[1].Range.Max, Axes[2].Range.Max); }

ImPlot3DPoint ImPlot3DPlot::RangeCenter() const {
    return ImPlot3DPoint((Axes[0].Range.Min + Axes[0].Range.Max) * 0.5f, (Axes[1].Range.Min + Axes[1].Range.Max) * 0.5f,
                         (Axes[2].Range.Min + Axes[2].Range.Max) * 0.5f);
}

void ImPlot3DPlot::SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max) {
    Axes[0].SetRange(min.x, max.x);
    Axes[1].SetRange(min.y, max.y);
    Axes[2].SetRange(min.z, max.z);
}

float ImPlot3DPlot::GetViewScale() const {
    return ImMin(PlotRect.GetWidth(), PlotRect.GetHeight()) / 1.8f * ImPlot3D::GImPlot3D->Style.ViewScaleFactor;
}

ImPlot3DPoint ImPlot3DPlot::GetBoxScale() const { return ImPlot3DPoint(Axes[0].NDCSize(), Axes[1].NDCSize(), Axes[2].NDCSize()); }

void ImPlot3DPlot::ApplyEqualAspect(ImAxis3D ref_axis) {
    double aspect = Axes[ref_axis].GetAspect();
    for (int i = 0; i < 3; i++) {
        if (i != ref_axis && !Axes[i].IsInputLocked()) {
            Axes[i].SetAspect(aspect);
        }
    }
}

//-----------------------------------------------------------------------------
// [SECTION] ImPlot3DStyle
//-----------------------------------------------------------------------------

ImPlot3DStyle::ImPlot3DStyle() {
    // Item style
    LineWeight = 1.0f;
    Marker = ImPlot3DMarker_None;
    MarkerSize = 4.0f;
    FillAlpha = 1.0f;
    // Plot style
    PlotDefaultSize = ImVec2(400, 400);
    PlotMinSize = ImVec2(200, 200);
    PlotPadding = ImVec2(10, 10);
    LabelPadding = ImVec2(5, 5);
    ViewScaleFactor = 1.0f;
    // Legend style
    LegendPadding = ImVec2(10, 10);
    LegendInnerPadding = ImVec2(5, 5);
    LegendSpacing = ImVec2(5, 0);
    // Colors
    ImPlot3D::StyleColorsAuto(this);
    Colormap = ImPlot3DColormap_Deep;
};

//-----------------------------------------------------------------------------
// [SECTION] Metrics
//-----------------------------------------------------------------------------

void ShowTicksMetrics(const ImPlot3DTicker& ticker) { ImGui::BulletText("Size: %d", ticker.TickCount()); }

void ShowAxisMetrics(const ImPlot3DAxis& axis) {
    ImGui::BulletText("Label: %s", axis.GetLabel());
    ImGui::BulletText("Flags: 0x%08X", axis.Flags);
    // Range
    ImGui::BulletText("Range: [%f,%f]", axis.Range.Min, axis.Range.Max);
    ImGui::BulletText("NDC Scale: %f", axis.NDCScale);
    ImGui::BulletText("NDC Range: [%f,%f]", -0.5f * axis.NDCScale, 0.5f * axis.NDCScale);
    ImGui::BulletText("Aspect: %f", axis.GetAspect());
    // Ticks
    ImGui::BulletText("ShowDefaultTicks: %s", axis.ShowDefaultTicks ? "true" : "false");
    // Fit data
    ImGui::BulletText("FitThisFrame: %s", axis.FitThisFrame ? "true" : "false");
    ImGui::BulletText("FitExtents: [%f,%f]", axis.FitExtents.Min, axis.FitExtents.Min);
    // Constraints
    ImGui::BulletText("ConstraintRange: [%f,%f]", axis.ConstraintRange.Min, axis.ConstraintRange.Min);
    ImGui::BulletText("ConstraintZoom: [%f,%f]", axis.ConstraintZoom.Min, axis.ConstraintZoom.Min);
    // User input
    ImGui::BulletText("Hovered: %s", axis.Hovered ? "true" : "false");
    ImGui::BulletText("Held: %s", axis.Held ? "true" : "false");

    if (ImGui::TreeNode("Ticks")) {
        ShowTicksMetrics(axis.Ticker);
        ImGui::TreePop();
    }
}

void ImPlot3D::ShowMetricsWindow(bool* p_popen) {
    static bool show_frame_rects = false;
    static bool show_canvas_rects = false;
    static bool show_plot_rects = false;
    static bool show_plot_box = false;
    static bool show_axis_line = false;
    static bool show_axis_corner_indexes = false;
    static bool show_axis_face_indexes = false;
    static bool show_axis_edge_indexes = false;
    static bool show_legend_rects = false;

    ImDrawList& fg = *ImGui::GetForegroundDrawList();

    ImPlot3DContext& gp = *GImPlot3D;
    ImGuiIO& io = ImGui::GetIO();
    ImGui::Begin("Metrics (ImPlot3D)", p_popen);
    ImGui::Text("ImPlot3D " IMPLOT3D_VERSION);
    ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
    ImGui::Text("Mouse Position: [%.0f,%.0f]", io.MousePos.x, io.MousePos.y);
    ImGui::Separator();
    if (ImGui::TreeNode("Tools")) {
        if (ImGui::Button("Bust Plot Cache"))
            BustPlotCache();
        ImGui::SameLine();
        if (ImGui::Button("Bust Item Cache"))
            BustItemCache();
        ImGui::Checkbox("Show Frame Rects", &show_frame_rects);
        ImGui::Checkbox("Show Canvas Rects", &show_canvas_rects);
        ImGui::Checkbox("Show Plot Rects", &show_plot_rects);
        ImGui::Checkbox("Show Plot Box", &show_plot_box);
        ImGui::Checkbox("Show Axis Line", &show_axis_line);
        ImGui::Checkbox("Show Axis Corner Indexes", &show_axis_corner_indexes);
        ImGui::Checkbox("Show Axis Face Indexes", &show_axis_face_indexes);
        ImGui::Checkbox("Show Axis Edge Indexes", &show_axis_edge_indexes);
        ImGui::Checkbox("Show Legend Rects", &show_legend_rects);
        ImGui::TreePop();
    }
    const int n_plots = gp.Plots.GetBufSize();
    bool active_faces[3];
    ImVec2 corners_pix[8];
    ImPlot3DPoint corners[8];
    int plane_2d = -1;
    int axis_corners[3][2];
    char buff[16];
    // Enum used to indicate how a certain type will be displayed
    enum class DisplayedType {
        Hidden,   // Hidden type that is not displayed. Used when the object should not be displayed. Will be used when:
                  // 1. 2D plot and this type should not be used,
                  // 2. The flag show_plot_box is disabled
        Active,   // Part of the faces of the box that are active
        NotActive // Part of the faces of the box that are not active when show_plot_box is active
    };

    // Render rectangles
    for (int p = 0; p < n_plots; ++p) {
        ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p);
        if (show_frame_rects)
            fg.AddRect(plot.FrameRect.Min, plot.FrameRect.Max, IM_COL32(255, 0, 255, 255));
        if (show_canvas_rects)
            fg.AddRect(plot.CanvasRect.Min, plot.CanvasRect.Max, IM_COL32(0, 255, 255, 255));
        if (show_plot_rects)
            fg.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, IM_COL32(255, 255, 0, 255));
        if (show_plot_box || show_axis_line || show_axis_corner_indexes || show_axis_face_indexes || show_axis_edge_indexes)
            GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners);
        if (show_plot_box || show_axis_edge_indexes) {
            // Determine which display type each of the edges are
            DisplayedType edge_types[12];
            for (int e = 0; e < 12; e++) {
                if (plane_2d == -1 && show_plot_box)
                    edge_types[e] = DisplayedType::NotActive;
                else
                    edge_types[e] = DisplayedType::Hidden;
            }
            for (int a = 0; a < 3; a++) {
                int face_idx = a + 3 * active_faces[a];
                for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++)
                    edge_types[face_edges[face_idx][i]] = DisplayedType::Active;
            }

            // Go through each edge and use the display type
            for (int e = 0; e < 12; e++) {
                int idx0 = edges[e][0];
                int idx1 = edges[e][1];

                if (show_plot_box) {
                    // Draw different lines depending on the type that the renderer thinks it is
                    if (edge_types[e] == DisplayedType::Active)
                        fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(255, 200, 0, 255));
                    else if (edge_types[e] == DisplayedType::NotActive)
                        fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(100, 255, 0, 125));
                    // If the render edge type is Hidden then there this edge does not get rendered
                }
                if (show_axis_edge_indexes) {
                    if (edge_types[e] == DisplayedType::Active || edge_types[e] == DisplayedType::NotActive) {
                        // Display the text in the middle between the points and at the same angle between the two points
                        ImVec2 edge_middle = (corners_pix[idx0] + corners_pix[idx1]) / 2;
                        ImVec2 point_difference = (corners_pix[idx1] - corners_pix[idx0]);
                        float angle = ImAtan2(-point_difference.y, point_difference.x);
                        // Adjust angle to keep labels upright
                        if (angle > IM_PI * 0.5f)
                            angle -= IM_PI;
                        if (angle < -IM_PI * 0.5f)
                            angle += IM_PI;

                        ImFormatString(buff, IM_ARRAYSIZE(buff), "E%d", e);
                        AddTextRotated(&fg, edge_middle, angle, IM_COL32(200, 0, 0, 200), buff);
                    }
                }
            }
        }
        if (show_axis_line) {
            // For each axis plot a line between the axis corners
            for (int a = 0; a < 3; a++) {
                if (plane_2d != -1 && a == plane_2d)
                    continue;
                int idx0 = axis_corners[a][0];
                int idx1 = axis_corners[a][1];

                // Draw axis line
                ImVec2 axis_start_pix = corners_pix[idx0];
                ImVec2 axis_end_pix = corners_pix[idx1];
                fg.AddLine(axis_start_pix, axis_end_pix, IM_COL32(0, 255, 255, 255));
            }
        }
        if (show_axis_corner_indexes) {
            // Determine which display type each of the corners are
            DisplayedType corner_types[8];
            for (int c = 0; c < 8; c++) {
                if (plane_2d == -1 && show_plot_box)
                    corner_types[c] = DisplayedType::NotActive;
                else
                    corner_types[c] = DisplayedType::Hidden;
            }
            for (int a = 0; a < 3; a++) {
                int face_idx = a + 3 * active_faces[a];
                for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++)
                    corner_types[faces[face_idx][i]] = DisplayedType::Active;
            }
            // Go through each corner and use the display type
            for (int c = 0; c < 8; c++) {
                if (corner_types[c] == DisplayedType::Active || corner_types[c] == DisplayedType::NotActive) {
                    ImVec2 corner = corners_pix[c];
                    ImFormatString(buff, IM_ARRAYSIZE(buff), "C%d", c);
                    AddTextRotated(&fg, corner, 0.0f, IM_COL32(0, 200, 0, 200), buff);
                }
            }
        }
        if (show_axis_face_indexes) {
            // Go through each axis and then face to display the face index
            for (int a = 0; a < 3; a++) {
                for (int f = 0; f < 2; f++) {
                    if ((plane_2d == -1 || a == plane_2d) && (f == int(active_faces[a]) || show_plot_box)) {
                        const int face_idx = a + 3 * f;
                        const int* face_indexes = faces[face_idx];
                        // Display the text in the middle of the square by determining the point between two of opposite corner pixels
                        ImVec2 middle_of_face_sqaure = (corners_pix[face_indexes[0]] + corners_pix[face_indexes[2]]) / 2;
                        ImFormatString(buff, IM_ARRAYSIZE(buff), "F%d", face_idx);
                        AddTextRotated(&fg, middle_of_face_sqaure, 0.0f, IM_COL32(0, 200, 200, 200), buff);
                    }
                }
            }
        }
        if (show_legend_rects && plot.Items.GetLegendCount() > 0)
            fg.AddRect(plot.Items.Legend.Rect.Min, plot.Items.Legend.Rect.Max, IM_COL32(255, 192, 0, 255));
    }
    if (ImGui::TreeNode("Plots", "Plots (%d)", n_plots)) {
        for (int p = 0; p < n_plots; ++p) {
            ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p);
            ImGui::PushID(p);
            if (ImGui::TreeNode("Plot", "Plot [0x%08X]", plot.ID)) {
                int n_items = plot.Items.GetItemCount();
                if (ImGui::TreeNode("Items", "Items (%d)", n_items)) {
                    for (int i = 0; i < n_items; ++i) {
                        ImPlot3DItem* item = plot.Items.GetItemByIndex(i);
                        ImGui::PushID(i);
                        if (ImGui::TreeNode("Item", "Item [0x%08X]", item->ID)) {
                            ImGui::Bullet();
                            ImGui::Checkbox("Show", &item->Show);
                            ImGui::Bullet();
                            ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color);
                            if (ImGui::ColorEdit4("Color", &temp.x, ImGuiColorEditFlags_NoInputs))
                                item->Color = ImGui::ColorConvertFloat4ToU32(temp);

                            ImGui::BulletText("NameOffset: %d", item->NameOffset);
                            ImGui::BulletText("Name: %s", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : "N/A");
                            ImGui::BulletText("Hovered: %s", item->LegendHovered ? "true" : "false");
                            ImGui::TreePop();
                        }
                        ImGui::PopID();
                    }
                    ImGui::TreePop();
                }

                if (ImGui::TreeNode("Axes")) {
                    // Get the axes parameters of this plot and use it to plot
                    GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners);

                    for (int a = 0; a < 3; ++a) {
                        if (plane_2d != -1 && plane_2d == a)
                            continue;
                        if (ImGui::TreeNode(axis_labels[a])) {
                            ShowAxisMetrics(plot.Axes[a]);
                            ImGui::TreePop();
                        }
                    }

                    if (plane_2d != -1)
                        ImGui::BulletText("Plane2D: %d %s", plane_2d, plane_labels[plane_2d]);
                    else {
                        int active_corner_index = Active3DFacesToAxisLookupIndex(active_faces);
                        ImGui::BulletText("3D Active Faces: [%s,%s,%s]=%d", active_faces[0] ? "X-max" : "X-min", active_faces[1] ? "Y-max" : "Y-min",
                                          active_faces[2] ? "Z-max" : "Z-min", active_corner_index);
                        ImGui::BulletText("3D Active Corner Lookup: [[%d,%d],[%d, %d],[%d, %d]]", axis_corners_lookup_3d[active_corner_index][0][0],
                                          axis_corners_lookup_3d[active_corner_index][0][1], axis_corners_lookup_3d[active_corner_index][1][0],
                                          axis_corners_lookup_3d[active_corner_index][1][1], axis_corners_lookup_3d[active_corner_index][2][0],
                                          axis_corners_lookup_3d[active_corner_index][2][1]);
                        ImGui::BulletText("3D Active Edges Lookup: [%d,%d,%d]", axis_edges_lookup_3d[active_corner_index][0],
                                          axis_edges_lookup_3d[active_corner_index][1], axis_edges_lookup_3d[active_corner_index][2]);
                    }

                    for (int a = 0; a < 3; a++)
                        ImGui::BulletText("%s Label Corners: [%d,%d]", axis_labels[a], axis_corners[a][0], axis_corners[a][1]);
                    for (int c = 0; c < 8; c++)
                        ImGui::BulletText("Corner %d: [%.2f,%.2f,%.2f] [%.2f,%.2f]", c, corners[c].x, corners[c].y, corners[c].z, corners_pix[c].x,
                                          corners_pix[c].y);

                    ImGui::TreePop();
                }

                ImGui::BulletText("Title: %s", plot.HasTitle() ? plot.GetTitle() : "none");
                ImGui::BulletText("Flags: 0x%08X", plot.Flags);
                ImGui::BulletText("Initialized: %s", plot.Initialized ? "true" : "false");
                ImGui::BulletText("Hovered: %s", plot.Hovered ? "true" : "false");
                ImGui::BulletText("Held: %s", plot.Held ? "true" : "false");
                ImGui::BulletText("HeldEdgeIdx: %d", plot.HeldEdgeIdx);
                ImGui::BulletText("HeldPlaneIdx: %d", plot.HeldPlaneIdx);
                ImGui::BulletText("LegendLocation: %s", GetShortLegendLocationName(plot.Items.Legend.Location));
                ImGui::BulletText("LegendHovered: %s", plot.Items.Legend.Hovered ? "true" : "false");
                ImGui::BulletText("LegendHeld: %s", plot.Items.Legend.Held ? "true" : "false");
                ImGui::BulletText("RotationCond: 0x%08X", plot.RotationCond);
                ImGui::BulletText("InitialRotation: [%.2f,%.2f,%.2f,%.2f]", plot.InitialRotation.x, plot.InitialRotation.y, plot.InitialRotation.z,
                                  plot.InitialRotation.w);
                ImGui::BulletText("Rotation: [%.2f,%.2f,%.2f,%.2f]", plot.Rotation.x, plot.Rotation.y, plot.Rotation.z, plot.Rotation.w);
                ImGui::BulletText("Animation: Time=%.4f RotationEnd=[%.2f,%.2f,%.2f,%.2f]", plot.AnimationTime, plot.RotationAnimationEnd.x,
                                  plot.RotationAnimationEnd.y, plot.Rotation.z, plot.RotationAnimationEnd.w);
                ImGui::BulletText("ViewScale: %.2f", plot.GetViewScale());

                ImGui::TreePop();
            }
            ImGui::PopID();
        }
        ImGui::TreePop();
    }

    if (ImGui::TreeNode("Colormaps")) {
        ImGui::BulletText("Colormaps:  %d", gp.ColormapData.Count);
        ImGui::BulletText("Memory: %d bytes", gp.ColormapData.Tables.Size * (int)(sizeof(gp.ColormapData.Tables.Data[0])));
        if (ImGui::TreeNode("Data")) {
            for (int m = 0; m < gp.ColormapData.Count; ++m) {
                if (ImGui::TreeNode(gp.ColormapData.GetName(m))) {
                    int count = gp.ColormapData.GetKeyCount(m);
                    int size = gp.ColormapData.GetTableSize(m);
                    bool qual = gp.ColormapData.IsQual(m);
                    ImGui::BulletText("Qualitative: %s", qual ? "true" : "false");
                    ImGui::BulletText("Key Count: %d", count);
                    ImGui::BulletText("Table Size: %d", size);
                    ImGui::Indent();

                    static float t = 0.5;
                    ImVec4 samp;
                    float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x;
                    ImGui::SetNextItemWidth(wid);
                    ColormapSlider("##Sample", &t, &samp, "%.3f", m);
                    ImGui::SameLine();
                    ImGui::ColorButton("Sampler", samp);
                    ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0));
                    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
                    for (int c = 0; c < size; ++c) {
                        ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m, c));
                        ImGui::PushID(m * 1000 + c);
                        ImGui::ColorButton("", col, 0, ImVec2(10, 10));
                        ImGui::PopID();
                        if ((c + 1) % 32 != 0 && c != size - 1)
                            ImGui::SameLine();
                    }
                    ImGui::PopStyleVar();
                    ImGui::PopStyleColor();
                    ImGui::Unindent();
                    ImGui::TreePop();
                }
            }
            ImGui::TreePop();
        }
        ImGui::TreePop();
    }
    ImGui::End();
}

//-----------------------------------------------------------------------------
// [SECTION] Obsolete API
//-----------------------------------------------------------------------------

#ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS

namespace ImPlot3D {

// OBSOLETED in v0.3
ImVec2 GetPlotPos() { return GetPlotRectPos(); }
ImVec2 GetPlotSize() { return GetPlotRectSize(); }

} // namespace ImPlot3D

#endif // #ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS

#endif // #ifndef IMGUI_DISABLE