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
//! Almost all nontrivial graphics programs are built on a foundation
//! of geometric classes. These classes represent mathematical
//! constructs like points, vectors, and rays.
//!
//! # Points
//!
//! A **point** is a zero-dimensional location in 2D or 3D space. The
//! **Point2** and **Point3** classes in **pbrt** represent points in
//! the obvious way: using x, y, z (in 3D) coordinates with respect to
//! a coordinate system. Although the same representation is used for
//! vectors, the fact that a point represents a position whereas a
//! vector represents a direction leads to a number of important
//! differences in how they are treated.
//!
//! ```rust
//! use pbrt::core::geometry::Point3;
//!
//! fn main() {
//!     let int_origin = Point3 { x: 0, y: 0, z: 0 };
//!     let float_origin = Point3 {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("int   {:?}", int_origin);
//!     println!("float {:?}", float_origin);
//! }
//! ```
//!
//! # Vectors
//!
//! **pbrt** provides both 2D and 3D **vector** classes. Both are
//! parameterized by the type of the underlying vector element, thus
//! making it easy to instantiate vectors of both integer and
//! floating-point types.
//!
//! ```rust
//! use pbrt::core::geometry::Vector3;
//!
//! fn main() {
//!     let int_null = Vector3 { x: 0, y: 0, z: 0 };
//!     let float_null = Vector3 {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("int   {:?}", int_null);
//!     println!("float {:?}", float_null);
//! }
//! ```
//!
//! # Normals
//!
//! A surface **normal** (or just normal) is a vector that is
//! perpendicular to a surface at a particular position. It can be
//! defined as the cross product of any two nonparallel vectors that
//! are tangent to the surface at a point. Although normals are
//! superficially similar to vectors, it is important to distinguish
//! between the two of them: because normals are defined in terms of
//! their relationship to a particular surface, they behave
//! differently than vectors in some situations, particularly when
//! applying transformations.
//!
//! ```rust
//! use pbrt::core::geometry::Normal3;
//!
//! fn main() {
//!     let int_null = Normal3 { x: 0, y: 0, z: 0 };
//!     let float_null = Normal3 {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!
//!     println!("int   {:?}", int_null);
//!     println!("float {:?}", float_null);
//! }
//! ```
//!
//! # Rays
//!
//! A **ray** is a semi-infinite line specified by its origin and
//! direction. **pbrt** represents a **Ray** with a **Point3f** for
//! the origin and a **Vector3f** for the direction. We only need rays
//! with floating-point origins and directions, so **Ray** isn't a
//! template class parameterized by an arbitrary type, as points,
//! vectors, and normals were.
//!
//! ```rust
//! use pbrt::core::geometry::{Ray, Point3f, Vector3f};
//!
//! fn main() {
//!     let origin = Point3f {
//!         x: -5.5,
//!         y: 2.75,
//!         z: 0.0,
//!     };
//!     let direction = Vector3f {
//!         x: 1.0,
//!         y: -8.75,
//!         z: 2.25,
//!     };
//!     let ray = Ray {
//!         o: origin,
//!         d: direction,
//!         t_max: std::f32::INFINITY,
//!         time: 0.0,
//!         medium: None,
//!         differential: None,
//!     };
//! }
//! ```
//!
//! ## RayDifferentials
//!
//! **RayDifferential** is a subclass of **Ray** that contains
//! additional information about two auxiliary rays. These extra rays
//! represent camera rays offset by one sample in the *x* and *y*
//! direction from the main ray on the film plane. By determining the
//! area that these three rays project on an object being shaded, the
//! **Texture** can estimate an area to average over for proper
//! antialiasing.
//!
//! In Rust we don't have inheritance, therefore we use an
//! **Option<RayDifferential>** in the **Ray** struct, which means the
//! additional information can be present (or not).
//!
//! # Bounding Boxes
//!
//! Many parts of the system operate on axis-aligned regions of
//! space. For example, multi-threading in **pbrt** is implemented by
//! subdividing the image into rectangular tiles that can be processed
//! independently, and the bounding volume hierarchy uses 3D boxes to
//! bound geometric primitives in the scene. The **Bounds2** and
//! **Bounds3** template classes are used to represent the extent of
//! these sort of regions. Both are parameterized by a type T that is
//! used to represent the coordinates of its extents.
//!
//!
//! ```rust
//! use pbrt::core::geometry::{Bounds3, Point3};
//!
//! fn main() {
//!     let int_origin = Point3 { x: 0, y: 0, z: 0 };
//!     let int_xyz111 = Point3 { x: 1, y: 1, z: 1 };
//!     let float_origin = Point3 {
//!         x: 0.0,
//!         y: 0.0,
//!         z: 0.0,
//!     };
//!     let float_xyz111 = Point3 {
//!         x: 1.0,
//!         y: 1.0,
//!         z: 1.0,
//!     };
//!     let int_unit_cube = Bounds3 {
//!         p_min: int_origin,
//!         p_max: int_xyz111,
//!     };
//!     let float_unit_cube = Bounds3 {
//!         p_min: float_origin,
//!         p_max: float_xyz111,
//!     };
//!
//!     println!("int   {:?}", int_unit_cube);
//!     println!("float {:?}", float_unit_cube);
//! }
//! ```

// std
use std;
use std::f32::consts::PI;
use std::ops::{
    Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign,
};
use std::sync::Arc;
// others
use num;
// pbrt
use crate::core::medium::Medium;
use crate::core::pbrt::Float;
use crate::core::pbrt::{clamp_t, gamma, lerp, next_float_down, next_float_up};

// see geometry.h

pub type Point2f = Point2<Float>;
pub type Point2i = Point2<i32>;
pub type Point3f = Point3<Float>;
pub type Point3i = Point3<i32>;
pub type Vector2f = Vector2<Float>;
pub type Vector2i = Vector2<i32>;
pub type Vector3f = Vector3<Float>;
pub type Vector3i = Vector3<i32>;
pub type Normal3f = Normal3<Float>;

#[derive(Debug, Default, Copy, Clone)]
pub struct Vector2<T> {
    pub x: T,
    pub y: T,
}

impl<T> Vector2<T> {
    pub fn has_nans(&self) -> bool
    where
        T: num::Float,
    {
        self.x.is_nan() || self.y.is_nan()
    }
    pub fn length_squared(&self) -> T
    where
        T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
    {
        self.x * self.x + self.y * self.y
    }
    pub fn length(&self) -> T
    where
        T: num::Float,
    {
        self.length_squared().sqrt()
    }
}

impl<T> Index<u8> for Vector2<T> {
    type Output = T;
    fn index(&self, index: u8) -> &T {
        match index {
            0 => &self.x,
            1 => &self.y,
            _ => panic!("Check failed: i >= 0 && i <= 1"),
        }
    }
}

impl<T> IndexMut<u8> for Vector2<T> {
    fn index_mut(&mut self, index: u8) -> &mut T {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            _ => panic!("Check failed: i >= 0 && i <= 1"),
        }
    }
}

impl<T> AddAssign<Vector2<T>> for Vector2<T>
where
    T: AddAssign,
{
    fn add_assign(&mut self, rhs: Vector2<T>) {
        self.x += rhs.x;
        self.y += rhs.y;
    }
}

impl<T> Add for Vector2<T>
where
    T: Copy + Add<T, Output = T>,
{
    type Output = Vector2<T>;
    fn add(self, rhs: Vector2<T>) -> Vector2<T> {
        Vector2::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl<T> SubAssign<Vector2<T>> for Vector2<T>
where
    T: SubAssign,
{
    fn sub_assign(&mut self, rhs: Vector2<T>) {
        self.x -= rhs.x;
        self.y -= rhs.y;
    }
}

impl<T> Sub for Vector2<T>
where
    T: Copy + Sub<T, Output = T>,
{
    type Output = Vector2<T>;
    fn sub(self, rhs: Vector2<T>) -> Vector2<T> {
        Vector2::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl<T> MulAssign<T> for Vector2<T>
where
    T: Copy + MulAssign,
{
    fn mul_assign(&mut self, rhs: T) {
        self.x *= rhs;
        self.y *= rhs;
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Div<Float> for Vector2<f32> {
    type Output = Vector2<f32>;
    fn div(self, rhs: Float) -> Vector2<f32> {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        Vector2::<f32> {
            x: self.x * inv,
            y: self.y * inv,
        }
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl DivAssign<Float> for Vector2<f32> {
    fn div_assign(&mut self, rhs: Float) {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        self.x *= inv;
        self.y *= inv;
    }
}

impl<T> From<Vector2<T>> for Point2<T> {
    fn from(v: Vector2<T>) -> Self {
        Point2::<T> { x: v.x, y: v.y }
    }
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
pub fn vec2_dot<T>(v1: &Vector2<T>, v2: &Vector2<T>) -> T
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
{
    v1.x * v2.x + v1.y * v2.y
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Vector3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T> Vector3<T> {
    pub fn has_nans(&self) -> bool
    where
        T: num::Float,
    {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
    }
    pub fn abs(&self) -> Vector3<T>
    where
        T: num::Float,
    {
        Vector3::<T> {
            x: self.x.abs(),
            y: self.y.abs(),
            z: self.z.abs(),
        }
    }
    pub fn length_squared(&self) -> T
    where
        T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
    {
        self.x * self.x + self.y * self.y + self.z * self.z
    }
    pub fn length(&self) -> T
    where
        T: num::Float,
    {
        self.length_squared().sqrt()
    }
}

impl Vector3<Float> {
    /// Compute a new vector pointing in the same direction but with unit
    /// length.
    #[inline]
    pub fn normalize(&self) -> Vector3<Float> {
        *self / self.length()
    }
}

impl<T> AddAssign<Vector3<T>> for Vector3<T>
where
    T: AddAssign,
{
    fn add_assign(&mut self, rhs: Vector3<T>) {
        self.x += rhs.x;
        self.y += rhs.y;
        self.z += rhs.z;
    }
}

impl<T> Add for Vector3<T>
where
    T: Copy + Add<T, Output = T>,
{
    type Output = Vector3<T>;
    fn add(self, rhs: Vector3<T>) -> Vector3<T> {
        Vector3::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
        }
    }
}

impl<T> SubAssign<Vector3<T>> for Vector3<T>
where
    T: SubAssign,
{
    fn sub_assign(&mut self, rhs: Vector3<T>) {
        self.x -= rhs.x;
        self.y -= rhs.y;
        self.z -= rhs.z;
    }
}

impl<T> Sub for Vector3<T>
where
    T: Copy + Sub<T, Output = T>,
{
    type Output = Vector3<T>;
    fn sub(self, rhs: Vector3<T>) -> Vector3<T> {
        Vector3::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

impl<T> Mul<T> for Vector3<T>
where
    T: Copy + Mul<T, Output = T>,
{
    type Output = Vector3<T>;
    #[inline]
    fn mul(self, rhs: T) -> Vector3<T>
    where
        T: Copy + Mul<T, Output = T>,
    {
        Vector3::<T> {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

impl<T> MulAssign<T> for Vector3<T>
where
    T: Copy + MulAssign,
{
    fn mul_assign(&mut self, rhs: T) {
        self.x *= rhs;
        self.y *= rhs;
        self.z *= rhs;
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Div<Float> for Vector3<f32> {
    type Output = Vector3<f32>;
    fn div(self, rhs: Float) -> Vector3<f32> {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        Vector3::<f32> {
            x: self.x * inv,
            y: self.y * inv,
            z: self.z * inv,
        }
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl DivAssign<Float> for Vector3<f32> {
    fn div_assign(&mut self, rhs: Float) {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        self.x *= inv;
        self.y *= inv;
        self.z *= inv;
    }
}

impl<T> Neg for Vector3<T>
where
    T: Copy + Neg<Output = T>,
{
    type Output = Vector3<T>;
    fn neg(self) -> Vector3<T> {
        Vector3::<T> {
            x: -self.x,
            y: -self.y,
            z: -self.z,
        }
    }
}

impl<T> Index<u8> for Vector3<T> {
    type Output = T;
    fn index(&self, index: u8) -> &T {
        match index {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

impl<T> IndexMut<u8> for Vector3<T> {
    fn index_mut(&mut self, index: u8) -> &mut T {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

impl<T> From<Point3<T>> for Vector3<T> {
    #[inline]
    fn from(p: Point3<T>) -> Self {
        Vector3::<T> {
            x: p.x,
            y: p.y,
            z: p.z,
        }
    }
}

impl<T> From<Normal3<T>> for Vector3<T> {
    fn from(n: Normal3<T>) -> Self {
        Vector3::<T> {
            x: n.x,
            y: n.y,
            z: n.z,
        }
    }
}

/// Product of the Euclidean magnitudes of the two vectors and the
/// cosine of the angle between them. A return value of zero means
/// both vectors are orthogonal, a value if one means they are
/// codirectional.
#[inline]
pub fn vec3_dot_vec3<T>(v1: &Vector3<T>, v2: &Vector3<T>) -> T
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
{
    v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
}

/// Product of the Euclidean magnitudes of a vector (and a normal) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn vec3_dot_nrm<T>(v1: &Vector3<T>, n2: &Normal3<T>) -> T
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
{
    // DCHECK(!v1.HasNaNs() && !n2.HasNaNs());
    v1.x * n2.x + v1.y * n2.y + v1.z * n2.z
}

/// Computes the absolute value of the dot product.
#[inline]
pub fn vec3_abs_dot_vec3<T>(v1: &Vector3<T>, v2: &Vector3<T>) -> T
where
    T: num::Float,
{
    vec3_dot_vec3(v1, v2).abs()
}

/// Computes the absolute value of the dot product.
pub fn vec3_abs_dot_nrm<T>(v1: &Vector3<T>, n2: &Normal3<T>) -> T
where
    T: num::Float,
{
    vec3_dot_nrm(v1, n2).abs()
}

/// Given two vectors in 3D, the cross product is a vector that is
/// perpendicular to both of them.
#[inline]
pub fn vec3_cross_vec3(v1: &Vector3f, v2: &Vector3f) -> Vector3f {
    let v1x: f64 = v1.x as f64;
    let v1y: f64 = v1.y as f64;
    let v1z: f64 = v1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((v1y * v2z) - (v1z * v2y)) as Float,
        y: ((v1z * v2x) - (v1x * v2z)) as Float,
        z: ((v1x * v2y) - (v1y * v2x)) as Float,
    }
}

/// Given a vectors and a normal in 3D, the cross product is a vector
/// that is perpendicular to both of them.
#[inline]
pub fn vec3_cross_nrm(v1: &Vector3f, v2: &Normal3f) -> Vector3f {
    let v1x: f64 = v1.x as f64;
    let v1y: f64 = v1.y as f64;
    let v1z: f64 = v1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((v1y * v2z) - (v1z * v2y)) as Float,
        y: ((v1z * v2x) - (v1x * v2z)) as Float,
        z: ((v1x * v2y) - (v1y * v2x)) as Float,
    }
}

/// Return the largest coordinate value.
pub fn vec3_max_component<T>(v: &Vector3<T>) -> T
where
    T: num::Float,
{
    v.x.max(v.y.max(v.z))
}

/// Return the index of the component with the largest value.
pub fn vec3_max_dimension<T>(v: &Vector3<T>) -> usize
where
    T: std::cmp::PartialOrd,
{
    if v.x > v.y {
        if v.x > v.z {
            0_usize
        } else {
            2_usize
        }
    } else if v.y > v.z {
        1_usize
    } else {
        2_usize
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn vec3_permute<T>(v: &Vector3<T>, x: usize, y: usize, z: usize) -> Vector3<T>
where
    T: Copy,
{
    let v3: [T; 3] = [v.x, v.y, v.z];
    let xp: T = v3[x];
    let yp: T = v3[y];
    let zp: T = v3[z];
    Vector3::<T> {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Construct a local coordinate system given only a single 3D vector.
#[inline]
pub fn vec3_coordinate_system(v1: &Vector3f, v2: &mut Vector3f, v3: &mut Vector3f) {
    if v1.x.abs() > v1.y.abs() {
        *v2 = Vector3f {
            x: -v1.z,
            y: 0.0 as Float,
            z: v1.x,
        } / (v1.x * v1.x + v1.z * v1.z).sqrt();
    } else {
        *v2 = Vector3f {
            x: 0.0 as Float,
            y: v1.z,
            z: -v1.y,
        } / (v1.y * v1.y + v1.z * v1.z).sqrt();
    }
    *v3 = vec3_cross_vec3(v1, &*v2);
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point2<T> {
    pub x: T,
    pub y: T,
}

impl<T> Point2<T> {
    pub fn has_nans(&self) -> bool
    where
        T: num::Float,
    {
        self.x.is_nan() || self.y.is_nan()
    }
}

impl<T> PartialEq for Point2<T>
where
    T: std::cmp::PartialOrd,
{
    fn eq(&self, rhs: &Point2<T>) -> bool {
        self.x == rhs.x && self.y == rhs.y
    }
}

impl<T> Add<Point2<T>> for Point2<T>
where
    T: Add<T, Output = T>,
{
    type Output = Point2<T>;
    fn add(self, rhs: Point2<T>) -> Point2<T> {
        Point2::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl<T> Add<Vector2<T>> for Point2<T>
where
    T: Add<T, Output = T>,
{
    type Output = Point2<T>;
    fn add(self, rhs: Vector2<T>) -> Point2<T> {
        Point2::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl<T> Sub<Point2<T>> for Point2<T>
where
    T: Sub<T, Output = T>,
{
    type Output = Vector2<T>;
    fn sub(self, rhs: Point2<T>) -> Vector2<T> {
        Vector2::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl<T> Sub<Vector2<T>> for Point2<T>
where
    T: Sub<T, Output = T>,
{
    type Output = Point2<T>;
    fn sub(self, rhs: Vector2<T>) -> Point2<T> {
        Point2::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl<T> Mul<T> for Point2<T>
where
    T: Copy + Mul<T, Output = T>,
{
    type Output = Point2<T>;
    fn mul(self, rhs: T) -> Point2<T>
    where
        T: Copy + Mul<T, Output = T>,
    {
        Point2::<T> {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

impl<T> Neg for Vector2<T>
where
    T: Copy + Neg<Output = T>,
{
    type Output = Vector2<T>;
    fn neg(self) -> Vector2<T> {
        Vector2::<T> {
            x: -self.x,
            y: -self.y,
        }
    }
}

impl<T> Index<u8> for Point2<T> {
    type Output = T;
    #[inline]
    fn index(&self, index: u8) -> &T {
        match index {
            0 => &self.x,
            1 => &self.y,
            _ => panic!("Check failed: i >= 0 && i <= 1"),
        }
    }
}

impl<T> IndexMut<u8> for Point2<T> {
    #[inline]
    fn index_mut(&mut self, index: u8) -> &mut T {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            _ => panic!("Check failed: i >= 0 && i <= 1"),
        }
    }
}

/// Apply floor operation component-wise.
pub fn pnt2_floor<T>(p: Point2<T>) -> Point2<T>
where
    T: num::Float,
{
    Point2 {
        x: p.x.floor(),
        y: p.y.floor(),
    }
}

/// Apply ceil operation component-wise.
pub fn pnt2_ceil<T>(p: Point2<T>) -> Point2<T>
where
    T: num::Float,
{
    Point2 {
        x: p.x.ceil(),
        y: p.y.ceil(),
    }
}

/// Apply std::cmp::min operation component-wise.
pub fn pnt2_min_pnt2<T>(pa: Point2<T>, pb: Point2<T>) -> Point2<T>
where
    T: Ord,
{
    Point2 {
        x: std::cmp::min(pa.x, pb.x),
        y: std::cmp::min(pa.y, pb.y),
    }
}

/// Apply std::cmp::max operation component-wise.
pub fn pnt2_max_pnt2<T>(pa: Point2<T>, pb: Point2<T>) -> Point2<T>
where
    T: Ord,
{
    Point2 {
        x: std::cmp::max(pa.x, pb.x),
        y: std::cmp::max(pa.y, pb.y),
    }
}

/// Given a bounding box and a point, the **bnd2_union_pnt2()**
/// function returns a new bounding box that encompasses that point as
/// well as the original box.
pub fn bnd2_union_pnt2<T>(b: &Bounds2<T>, p: Point2<T>) -> Bounds2<T>
where
    T: num::Float,
{
    let p_min: Point2<T> = Point2::<T> {
        x: b.p_min.x.min(p.x),
        y: b.p_min.y.min(p.y),
    };
    let p_max: Point2<T> = Point2::<T> {
        x: b.p_max.x.max(p.x),
        y: b.p_max.y.max(p.y),
    };
    Bounds2 { p_min, p_max }
}

/// Determine if a given point is inside the bounding box.
pub fn pnt2_inside_bnd2<T>(pt: Point2<T>, b: &Bounds2<T>) -> bool
where
    T: PartialOrd,
{
    pt.x >= b.p_min.x && pt.x <= b.p_max.x && pt.y >= b.p_min.y && pt.y <= b.p_max.y
}

/// Is a 2D point inside a 2D bound?
pub fn pnt2_inside_exclusive<T>(pt: Point2<T>, b: &Bounds2<T>) -> bool
where
    T: PartialOrd,
{
    pt.x >= b.p_min.x && pt.x < b.p_max.x && pt.y >= b.p_min.y && pt.y < b.p_max.y
}

/// Pads the bounding box by a constant factor in both dimensions.
pub fn bnd2_expand(b: &Bounds2f, delta: Float) -> Bounds2f {
    Bounds2f {
        p_min: b.p_min - Vector2f { x: delta, y: delta },
        p_max: b.p_max + Vector2f { x: delta, y: delta },
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Point3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T> Point3<T> {
    pub fn has_nans(&self) -> bool
    where
        T: num::Float,
    {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan()
    }
}

impl<T> AddAssign<Point3<T>> for Point3<T>
where
    T: AddAssign,
{
    fn add_assign(&mut self, rhs: Point3<T>) {
        self.x += rhs.x;
        self.y += rhs.y;
        self.z += rhs.z;
    }
}

impl<T> Add<Point3<T>> for Point3<T>
where
    T: Add<T, Output = T>,
{
    type Output = Point3<T>;
    fn add(self, rhs: Point3<T>) -> Point3<T> {
        Point3::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
        }
    }
}

impl<T> Add<Vector3<T>> for Point3<T>
where
    T: Add<T, Output = T>,
{
    type Output = Point3<T>;
    fn add(self, rhs: Vector3<T>) -> Point3<T> {
        Point3::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
        }
    }
}

impl<T> AddAssign<Vector3<T>> for Point3<T>
where
    T: AddAssign,
{
    fn add_assign(&mut self, rhs: Vector3<T>) {
        self.x += rhs.x;
        self.y += rhs.y;
        self.z += rhs.z;
    }
}

impl<T> Sub<Point3<T>> for Point3<T>
where
    T: Sub<T, Output = T>,
{
    type Output = Vector3<T>;
    fn sub(self, rhs: Point3<T>) -> Vector3<T> {
        Vector3::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

impl<T> Sub<Vector3<T>> for Point3<T>
where
    T: Sub<T, Output = T>,
{
    type Output = Point3<T>;
    fn sub(self, rhs: Vector3<T>) -> Point3<T> {
        Point3::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

impl<T> Mul<T> for Point3<T>
where
    T: Copy + Mul<T, Output = T>,
{
    type Output = Point3<T>;
    fn mul(self, rhs: T) -> Point3<T>
    where
        T: Copy + Mul<T, Output = T>,
    {
        Point3::<T> {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

impl<T> MulAssign<T> for Point3<T>
where
    T: Copy + MulAssign,
{
    fn mul_assign(&mut self, rhs: T) {
        self.x *= rhs;
        self.y *= rhs;
        self.z *= rhs;
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Div<Float> for Point3<f32> {
    type Output = Point3<f32>;
    fn div(self, rhs: Float) -> Point3<f32> {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        Point3::<f32> {
            x: self.x * inv,
            y: self.y * inv,
            z: self.z * inv,
        }
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl DivAssign<Float> for Point3<f32> {
    fn div_assign(&mut self, rhs: Float) {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        self.x *= inv;
        self.y *= inv;
        self.z *= inv;
    }
}

impl<T> Index<u8> for Point3<T> {
    type Output = T;
    fn index(&self, index: u8) -> &T {
        match index {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

impl<T> IndexMut<u8> for Point3<T> {
    fn index_mut(&mut self, index: u8) -> &mut T {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

/// Permute the coordinate values according to the povided
/// permutation.
pub fn pnt3_permute<T>(v: &Point3<T>, x: usize, y: usize, z: usize) -> Point3<T>
where
    T: Copy,
{
    let v3: [T; 3] = [v.x, v.y, v.z];
    let xp: T = v3[x];
    let yp: T = v3[y];
    let zp: T = v3[z];
    Point3::<T> {
        x: xp,
        y: yp,
        z: zp,
    }
}

/// Interpolate linearly between two provided points.
pub fn pnt3_lerp(t: Float, p0: &Point3f, p1: &Point3f) -> Point3f {
    *p0 * (1.0 as Float - t) as Float + *p1 * t
}

/// Apply floor operation component-wise.
pub fn pnt3_floor<T>(p: &Point3<T>) -> Point3<T>
where
    T: num::Float,
{
    Point3 {
        x: p.x.floor(),
        y: p.y.floor(),
        z: p.z.floor(),
    }
}

/// Apply ceil operation component-wise.
pub fn pnt3_ceil<T>(p: &Point3<T>) -> Point3<T>
where
    T: num::Float,
{
    Point3 {
        x: p.x.ceil(),
        y: p.y.ceil(),
        z: p.z.ceil(),
    }
}

/// Apply abs operation component-wise.
pub fn pnt3_abs<T>(p: &Point3<T>) -> Point3<T>
where
    T: num::Float,
{
    Point3 {
        x: p.x.abs(),
        y: p.y.abs(),
        z: p.z.abs(),
    }
}

/// The distance between two points is the length of the vector
/// between them.
pub fn pnt3_distance<T>(p1: &Point3<T>, p2: &Point3<T>) -> T
where
    T: num::Float + Sub<T, Output = T>,
{
    (*p1 - *p2).length()
}

/// The distance squared between two points is the length of the
/// vector between them squared.
pub fn pnt3_distance_squared<T>(p1: &Point3<T>, p2: &Point3<T>) -> T
where
    T: num::Float + Sub<T, Output = T>,
{
    (*p1 - *p2).length_squared()
}

/// When tracing spawned rays leaving the intersection point p, we
/// offset their origins enough to ensure that they are past the
/// boundary of the error box and thus won't incorrectly re-intersect
/// the surface.
pub fn pnt3_offset_ray_origin(
    p: &Point3f,
    p_error: &Vector3f,
    n: &Normal3f,
    w: &Vector3f,
) -> Point3f {
    //     Float d = Dot(Abs(n), pError);
    let d: Float = nrm_dot_vec3(&nrm_abs(n), p_error);
    // #ifdef PBRT_FLOAT_AS_DOUBLE
    //     // We have tons of precision; for now bump up the offset a bunch just
    //     // to be extra sure that we start on the right side of the surface
    //     // (In case of any bugs in the epsilons code...)
    //     d *= 1024.;
    // #endif
    let mut offset: Vector3f = Vector3f::from(*n) * d;
    if vec3_dot_nrm(w, n) < 0.0 as Float {
        offset = -offset;
    }
    let mut po: Point3f = *p + offset;
    // round offset point _po_ away from _p_
    for i in 0..3 {
        if offset[i] > 0.0 as Float {
            po[i] = next_float_up(po[i]);
        } else if offset[i] < 0.0 as Float {
            po[i] = next_float_down(po[i]);
        }
    }
    po
}

/// Calculate appropriate direction vector from two angles.
pub fn spherical_direction(sin_theta: Float, cos_theta: Float, phi: Float) -> Vector3f {
    Vector3f {
        x: sin_theta * phi.cos(),
        y: sin_theta * phi.sin(),
        z: cos_theta,
    }
}

/// Take three basis vectors representing the x, y, and z axes and
/// return the appropriate direction vector with respect to the
/// coordinate frame defined by them.
pub fn spherical_direction_vec3(
    sin_theta: Float,
    cos_theta: Float,
    phi: Float,
    x: &Vector3f,
    y: &Vector3f,
    z: &Vector3f,
) -> Vector3f {
    *x * (sin_theta * phi.cos()) + *y * (sin_theta * phi.sin()) + *z * cos_theta
}

/// Conversion of a direction to spherical angles. Note that
/// **spherical_theta()** assumes that the vector **v** has been
/// normalized before being passed in.
pub fn spherical_theta(v: &Vector3f) -> Float {
    clamp_t(v.z, -1.0 as Float, 1.0 as Float).acos()
}

/// Conversion of a direction to spherical angles.
pub fn spherical_phi(v: &Vector3f) -> Float {
    let p: Float = v.y.atan2(v.x);
    if p < 0.0 as Float {
        p + 2.0 as Float * PI
    } else {
        p
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Normal3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl Normal3<Float> {
    /// Compute a new normal pointing in the same direction but with unit
    /// length.
    #[inline]
    pub fn normalize(&self) -> Normal3<Float> {
        *self / self.length()
    }
}

impl<T> Add for Normal3<T>
where
    T: Copy + Add<T, Output = T>,
{
    type Output = Normal3<T>;
    fn add(self, rhs: Normal3<T>) -> Normal3<T> {
        Normal3::<T> {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
        }
    }
}

impl<T> Sub for Normal3<T>
where
    T: Copy + Sub<T, Output = T>,
{
    type Output = Normal3<T>;
    fn sub(self, rhs: Normal3<T>) -> Normal3<T> {
        Normal3::<T> {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

impl<T> Mul<T> for Normal3<T>
where
    T: Copy + Mul<T, Output = T>,
{
    type Output = Normal3<T>;
    fn mul(self, rhs: T) -> Normal3<T>
    where
        T: Copy + Mul<T, Output = T>,
    {
        Normal3::<T> {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

impl<T> MulAssign<T> for Normal3<T>
where
    T: Copy + MulAssign,
{
    fn mul_assign(&mut self, rhs: T) {
        self.x *= rhs;
        self.y *= rhs;
        self.z *= rhs;
    }
}

impl<T> Neg for Normal3<T>
where
    T: Copy + Neg<Output = T>,
{
    type Output = Normal3<T>;
    fn neg(self) -> Normal3<T> {
        Normal3::<T> {
            x: -self.x,
            y: -self.y,
            z: -self.z,
        }
    }
}

impl<T> Index<u8> for Normal3<T> {
    type Output = T;
    fn index(&self, index: u8) -> &T {
        match index {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

impl<T> IndexMut<u8> for Normal3<T> {
    fn index_mut(&mut self, index: u8) -> &mut T {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("Check failed: i >= 0 && i <= 2"),
        }
    }
}

impl<T> Normal3<T> {
    pub fn length_squared(&self) -> T
    where
        T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
    {
        self.x * self.x + self.y * self.y + self.z * self.z
    }
    pub fn length(&self) -> T
    where
        T: num::Float,
    {
        self.length_squared().sqrt()
    }
}

impl<T> PartialEq for Normal3<T>
where
    T: std::cmp::PartialOrd,
{
    fn eq(&self, rhs: &Normal3<T>) -> bool {
        self.x == rhs.x && self.y == rhs.y && self.z == rhs.z
    }
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Div<Float> for Normal3<f32> {
    type Output = Normal3<f32>;
    fn div(self, rhs: Float) -> Normal3<f32> {
        assert_ne!(rhs, 0.0 as Float);
        let inv: Float = 1.0 as Float / rhs;
        Normal3::<f32> {
            x: self.x * inv,
            y: self.y * inv,
            z: self.z * inv,
        }
    }
}

impl<T> From<Vector3<T>> for Normal3<T> {
    fn from(v: Vector3<T>) -> Self {
        Normal3::<T> {
            x: v.x,
            y: v.y,
            z: v.z,
        }
    }
}

/// Given a normal and a vector in 3D, the cross product is a vector
/// that is perpendicular to both of them.
#[inline]
pub fn nrm_cross_vec3(n1: &Normal3f, v2: &Vector3f) -> Vector3f {
    let n1x: f64 = n1.x as f64;
    let n1y: f64 = n1.y as f64;
    let n1z: f64 = n1.z as f64;
    let v2x: f64 = v2.x as f64;
    let v2y: f64 = v2.y as f64;
    let v2z: f64 = v2.z as f64;
    Vector3f {
        x: ((n1y * v2z) - (n1z * v2y)) as Float,
        y: ((n1z * v2x) - (n1x * v2z)) as Float,
        z: ((n1x * v2y) - (n1y * v2x)) as Float,
    }
}

/// Product of the Euclidean magnitudes of a normal (and another
/// normal) and the cosine of the angle between them. A return value
/// of zero means both are orthogonal, a value if one means they are
/// codirectional.
pub fn nrm_dot_nrm<T>(n1: &Normal3<T>, n2: &Normal3<T>) -> T
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
{
    n1.x * n2.x + n1.y * n2.y + n1.z * n2.z
}

/// Product of the Euclidean magnitudes of a normal (and a vector) and
/// the cosine of the angle between them. A return value of zero means
/// both are orthogonal, a value if one means they are codirectional.
pub fn nrm_dot_vec3<T>(n1: &Normal3<T>, v2: &Vector3<T>) -> T
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T>,
{
    n1.x * v2.x + n1.y * v2.y + n1.z * v2.z
}

/// Computes the absolute value of the dot product.
pub fn nrm_abs_dot_vec3<T>(n1: &Normal3<T>, v2: &Vector3<T>) -> T
where
    T: num::Float,
{
    nrm_dot_vec3(n1, v2).abs()
}

/// Return normal with the absolute value of each coordinate.
pub fn nrm_abs<T>(n: &Normal3<T>) -> Normal3<T>
where
    T: num::Float,
{
    Normal3::<T> {
        x: n.x.abs(),
        y: n.y.abs(),
        z: n.z.abs(),
    }
}

/// Flip a surface normal so that it lies in the same hemisphere as a
/// given vector.
pub fn nrm_faceforward_vec3(n: &Normal3f, v: &Vector3f) -> Normal3f {
    if nrm_dot_vec3(n, v) < 0.0 as Float {
        -(*n)
    } else {
        *n
    }
}

/// Flip a surface normal so that it lies in the same hemisphere as a
/// given normal.
pub fn nrm_faceforward_nrm(n: &Normal3f, n2: &Normal3f) -> Normal3f {
    if nrm_dot_nrm(n, n2) < 0.0 as Float {
        -(*n)
    } else {
        *n
    }
}

pub type Bounds2f = Bounds2<Float>;
pub type Bounds2i = Bounds2<i32>;
pub type Bounds3f = Bounds3<Float>;
pub type Bounds3i = Bounds3<i32>;

#[derive(Debug, Default, Copy, Clone)]
pub struct Bounds2<T> {
    pub p_min: Point2<T>,
    pub p_max: Point2<T>,
}

impl<T> Bounds2<T> {
    pub fn new(p1: Point2<T>, p2: Point2<T>) -> Self
    where
        T: Copy + Ord,
    {
        let p_min: Point2<T> = Point2::<T> {
            x: std::cmp::min(p1.x, p2.x),
            y: std::cmp::min(p1.y, p2.y),
        };
        let p_max: Point2<T> = Point2::<T> {
            x: std::cmp::max(p1.x, p2.x),
            y: std::cmp::max(p1.y, p2.y),
        };
        Bounds2::<T> { p_min, p_max }
    }
    pub fn diagonal(&self) -> Vector2<T>
    where
        T: Copy + Sub<T, Output = T>,
    {
        self.p_max - self.p_min
    }
    pub fn area(&self) -> T
    where
        T: Copy + Sub<T, Output = T> + Mul<T, Output = T>,
    {
        let d: Vector2<T> = self.p_max - self.p_min;
        d.x * d.y
    }
}

impl Bounds2<Float> {
    pub fn lerp(&self, t: Point2f) -> Point2f {
        Point2f {
            x: lerp(t.x, self.p_min.x, self.p_max.x),
            y: lerp(t.y, self.p_min.y, self.p_max.y),
        }
    }
    pub fn offset(&self, p: Point2f) -> Vector2f {
        let mut o: Vector2f = p - self.p_min;
        if self.p_max.x > self.p_min.x {
            o.x /= self.p_max.x - self.p_min.x;
        }
        if self.p_max.y > self.p_min.y {
            o.y /= self.p_max.y - self.p_min.y;
        }
        o
    }
}

pub struct Bounds2Iterator<'a> {
    p: Point2i,
    bounds: &'a Bounds2i,
}

impl<'a> Iterator for Bounds2Iterator<'a> {
    type Item = Point2i;

    fn next(&mut self) -> Option<Point2i> {
        self.p.x += 1;
        if self.p.x == self.bounds.p_max.x {
            self.p.x = self.bounds.p_min.x;
            self.p.y += 1;
        }
        if self.p.y == self.bounds.p_max.y {
            None
        } else {
            Some(self.p)
        }
    }
}

impl<'a> IntoIterator for &'a Bounds2i {
    type Item = Point2i;
    type IntoIter = Bounds2Iterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Bounds2Iterator {
            // need to start 1 before p_min.x as next() will be called
            // to get the first element
            p: Point2i {
                x: self.p_min.x - 1,
                y: self.p_min.y,
            },
            bounds: self,
        }
    }
}

/// The intersection of two bounding boxes can be found by computing
/// the maximum of their two respective minimum coordinates and the
/// minimum of their maximum coordinates.
pub fn bnd2_intersect_bnd2<T>(b1: &Bounds2<T>, b2: &Bounds2<T>) -> Bounds2<T>
where
    T: Copy + Ord,
{
    Bounds2::<T> {
        p_min: Point2::<T> {
            x: std::cmp::max(b1.p_min.x, b2.p_min.x),
            y: std::cmp::max(b1.p_min.y, b2.p_min.y),
        },
        p_max: Point2::<T> {
            x: std::cmp::min(b1.p_max.x, b2.p_max.x),
            y: std::cmp::min(b1.p_max.y, b2.p_max.y),
        },
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Bounds3<T> {
    pub p_min: Point3<T>,
    pub p_max: Point3<T>,
}

// work around bug
// https://github.com/rust-lang/rust/issues/40395
impl Default for Bounds3<f32> {
    fn default() -> Bounds3<f32> {
        let min_num: Float = std::f32::MIN;
        let max_num: Float = std::f32::MAX;
        // Bounds3f
        Bounds3::<f32> {
            p_min: Point3f {
                x: max_num,
                y: max_num,
                z: max_num,
            },
            p_max: Point3f {
                x: min_num,
                y: min_num,
                z: min_num,
            },
        }
    }
}

impl<T> Bounds3<T> {
    pub fn new(p1: Point3<T>, p2: Point3<T>) -> Self
    where
        T: num::Float,
    {
        let p_min: Point3<T> = Point3::<T> {
            x: p1.x.min(p2.x),
            y: p1.y.min(p2.y),
            z: p1.z.min(p2.z),
        };
        let p_max: Point3<T> = Point3::<T> {
            x: p1.x.max(p2.x),
            y: p1.y.max(p2.y),
            z: p1.z.max(p2.z),
        };
        Bounds3::<T> { p_min, p_max }
    }
    pub fn corner(&self, corner: u8) -> Point3<T>
    where
        T: Copy,
    {
        // assert!(corner >= 0_u8);
        assert!(corner < 8_u8);
        let x: T;
        if corner & 1 == 0 {
            x = self.p_min.x;
        } else {
            x = self.p_max.x;
        }
        let y: T;
        if corner & 2 == 0 {
            y = self.p_min.y;
        } else {
            y = self.p_max.y;
        }
        let z: T;
        if corner & 4 == 0 {
            z = self.p_min.z;
        } else {
            z = self.p_max.z;
        }
        Point3::<T> { x, y, z }
    }
    pub fn diagonal(&self) -> Vector3<T>
    where
        T: Copy + Sub<T, Output = T>,
    {
        self.p_max - self.p_min
    }
    pub fn surface_area(&self) -> T
    where
        T: Copy + Add<T, Output = T> + Sub<T, Output = T> + Mul<T, Output = T>,
    {
        let d: Vector3<T> = self.diagonal();
        // 2 * (d.x * d.y + d.x * d.z + d.y * d.z)
        let r: T = d.x * d.y + d.x * d.z + d.y * d.z;
        r + r // avoid '2 *'
    }
    pub fn maximum_extent(&self) -> u8
    where
        T: Copy + std::cmp::PartialOrd + Sub<T, Output = T>,
    {
        let d: Vector3<T> = self.diagonal();
        if d.x > d.y && d.x > d.z {
            0_u8
        } else if d.y > d.z {
            1_u8
        } else {
            2_u8
        }
    }
    pub fn offset(&self, p: &Point3<T>) -> Vector3<T>
    where
        T: Copy + std::cmp::PartialOrd + Sub<T, Output = T> + DivAssign<T>,
    {
        let mut o: Vector3<T> = *p - self.p_min;
        if self.p_max.x > self.p_min.x {
            o.x /= self.p_max.x - self.p_min.x;
        }
        if self.p_max.y > self.p_min.y {
            o.y /= self.p_max.y - self.p_min.y;
        }
        if self.p_max.z > self.p_min.z {
            o.z /= self.p_max.z - self.p_min.z;
        }
        o
    }
    pub fn bounding_sphere(b: &Bounds3f, center: &mut Point3f, radius: &mut Float) {
        let p_min: Point3f = b.p_min as Point3f;
        let p_max: Point3f = b.p_max as Point3f;
        let sum: Point3f = p_min + p_max;
        *center = sum / 2.0;
        let center_copy: Point3f = *center as Point3f;
        let is_inside: bool = pnt3_inside_bnd3(&center_copy, b);
        if is_inside {
            *radius = pnt3_distance(&center_copy, &p_max);
        } else {
            *radius = 0.0;
        }
    }
}

impl Bounds3<Float> {
    pub fn lerp(&self, t: &Point3f) -> Point3f {
        Point3f {
            x: lerp(t.x, self.p_min.x as Float, self.p_max.x as Float),
            y: lerp(t.y, self.p_min.y as Float, self.p_max.y as Float),
            z: lerp(t.z, self.p_min.z as Float, self.p_max.z as Float),
        }
    }
    pub fn intersect_b(&self, ray: &Ray, hitt0: &mut Float, hitt1: &mut Float) -> bool {
        let mut t0: Float = 0.0;
        let mut t1: Float = ray.t_max;
        for i in 0..3 {
            // update interval for _i_th bounding box slab
            let inv_ray_dir: Float = 1.0 as Float / ray.d[i];
            let mut t_near: Float = (self.p_min[i] - ray.o[i]) * inv_ray_dir;
            let mut t_far: Float = (self.p_max[i] - ray.o[i]) * inv_ray_dir;
            // update parametric interval from slab intersection $t$ values
            if t_near > t_far {
                std::mem::swap(&mut t_near, &mut t_far);
            }
            // update _t_far_ to ensure robust ray--bounds intersection
            t_far *= 1.0 as Float + 2.0 as Float * gamma(3_i32);
            if t_near > t0 {
                t0 = t_near;
            }
            if t_far < t1 {
                t1 = t_far;
            }
            if t0 > t1 {
                return false;
            }
        }
        *hitt0 = t0;
        *hitt1 = t1;
        true
    }
    #[inline]
    pub fn intersect_p(&self, ray: &Ray, inv_dir: &Vector3f, dir_is_neg: &[u8; 3]) -> bool {
        // check for ray intersection against $x$ and $y$ slabs
        let mut t_min: Float = (self[dir_is_neg[0]].x - ray.o.x) * inv_dir.x;
        let mut t_max: Float = (self[1_u8 - dir_is_neg[0]].x - ray.o.x) * inv_dir.x;
        let ty_min: Float = (self[dir_is_neg[1]].y - ray.o.y) * inv_dir.y;
        let mut ty_max: Float = (self[1_u8 - dir_is_neg[1]].y - ray.o.y) * inv_dir.y;
        // update _t_max_ and _ty_max_ to ensure robust bounds intersection
        t_max *= 1.0 + 2.0 * gamma(3_i32);
        ty_max *= 1.0 + 2.0 * gamma(3_i32);
        if t_min > ty_max || ty_min > t_max {
            return false;
        }
        if ty_min > t_min {
            t_min = ty_min;
        }
        if ty_max < t_max {
            t_max = ty_max;
        }
        // check for ray intersection against $z$ slab
        let tz_min: Float = (self[dir_is_neg[2]].z - ray.o.z) * inv_dir.z;
        let mut tz_max: Float = (self[1_u8 - dir_is_neg[2]].z - ray.o.z) * inv_dir.z;
        // update _tz_max_ to ensure robust bounds intersection
        tz_max *= 1.0 + 2.0 * gamma(3_i32);
        if t_min > tz_max || tz_min > t_max {
            return false;
        }
        if tz_min > t_min {
            t_min = tz_min;
        }
        if tz_max < t_max {
            t_max = tz_max;
        }
        (t_min < ray.t_max) && (t_max > 0.0)
    }
}

impl<T> Index<u8> for Bounds3<T> {
    type Output = Point3<T>;
    #[inline]
    fn index(&self, i: u8) -> &Point3<T> {
        match i {
            0 => &self.p_min,
            1 => &self.p_max,
            _ => panic!("Invalid index!"),
        }
    }
}

// /// Minimum squared distance from point to box; returns zero if point
// /// is inside.
// pub fn pnt3_distance_squared_bnd3(p: Point3f, b: Bounds3f) -> Float {
//     let dx: Float = (b.p_min.x - p.x).max(num::Zero::zero()).max(p.x - b.p_max.x);
//     let dy: Float = (b.p_min.y - p.y).max(num::Zero::zero()).max(p.y - b.p_max.y);
//     let dz: Float = (b.p_min.z - p.z).max(num::Zero::zero()).max(p.z - b.p_max.z);
//     dx * dx + dy * dy + dz * dz
// }

// /// Minimum distance from point to box; returns zero if point is
// /// inside.
// pub fn pnt3_distance_bnd3(p: Point3f, b: Bounds3f) -> Float {
//     pnt3_distance_squared_bnd3(p, b).sqrt()
// }

/// Given a bounding box and a point, the **bnd3_union_pnt3()**
/// function returns a new bounding box that encompasses that point as
/// well as the original box.
pub fn bnd3_union_pnt3<T>(b: &Bounds3<T>, p: &Point3<T>) -> Bounds3<T>
where
    T: num::Float,
{
    let p_min: Point3<T> = Point3::<T> {
        x: b.p_min.x.min(p.x),
        y: b.p_min.y.min(p.y),
        z: b.p_min.z.min(p.z),
    };
    let p_max: Point3<T> = Point3::<T> {
        x: b.p_max.x.max(p.x),
        y: b.p_max.y.max(p.y),
        z: b.p_max.z.max(p.z),
    };
    Bounds3 { p_min, p_max }
}

/// Construct a new box that bounds the space encompassed by two other
/// bounding boxes.
pub fn bnd3_union_bnd3<T>(b1: &Bounds3<T>, b2: &Bounds3<T>) -> Bounds3<T>
where
    T: num::Float,
{
    let p_min: Point3<T> = Point3::<T> {
        x: b1.p_min.x.min(b2.p_min.x),
        y: b1.p_min.y.min(b2.p_min.y),
        z: b1.p_min.z.min(b2.p_min.z),
    };
    let p_max: Point3<T> = Point3::<T> {
        x: b1.p_max.x.max(b2.p_max.x),
        y: b1.p_max.y.max(b2.p_max.y),
        z: b1.p_max.z.max(b2.p_max.z),
    };
    Bounds3 { p_min, p_max }
}

/// Determine if a given point is inside the bounding box.
pub fn pnt3_inside_bnd3(p: &Point3f, b: &Bounds3f) -> bool {
    p.x >= b.p_min.x
        && p.x <= b.p_max.x
        && p.y >= b.p_min.y
        && p.y <= b.p_max.y
        && p.z >= b.p_min.z
        && p.z <= b.p_max.z
}

/// Is a 3D point inside a 3D bound?
pub fn pnt3i_inside_exclusive(p: &Point3i, b: &Bounds3i) -> bool {
    p.x >= b.p_min.x
        && p.x < b.p_max.x
        && p.y >= b.p_min.y
        && p.y < b.p_max.y
        && p.z >= b.p_min.z
        && p.z < b.p_max.z
}

/// Is a 3D point inside a 3D bound?
pub fn pnt3f_inside_exclusive(p: &Point3f, b: &Bounds3f) -> bool {
    p.x >= b.p_min.x
        && p.x < b.p_max.x
        && p.y >= b.p_min.y
        && p.y < b.p_max.y
        && p.z >= b.p_min.z
        && p.z < b.p_max.z
}

/// Pads the bounding box by a constant factor in all dimensions.
pub fn bnd3_expand(b: &Bounds3f, delta: Float) -> Bounds3f {
    Bounds3f::new(
        b.p_min
            - Vector3f {
                x: delta,
                y: delta,
                z: delta,
            },
        b.p_max
            + Vector3f {
                x: delta,
                y: delta,
                z: delta,
            },
    )
}

#[derive(Default, Clone)]
pub struct Ray {
    /// origin
    pub o: Point3f,
    /// direction
    pub d: Vector3f,
    /// limits the ray to a segment along its infinite extent
    pub t_max: Float,
    /// used for animations
    pub time: Float,
    pub medium: Option<Arc<Medium>>,
    /// in C++: 'class RayDifferential : public Ray'
    pub differential: Option<RayDifferential>,
}

impl Ray {
    // Point3f operator()(Float t) const { return o + d * t; }
    pub fn position(&self, t: Float) -> Point3f {
        self.o + self.d * t
    }
    // from class RayDifferential
    pub fn scale_differentials(&mut self, s: Float) {
        if let Some(d) = self.differential.iter_mut().next() {
            d.rx_origin = self.o + (d.rx_origin - self.o) * s;
            d.ry_origin = self.o + (d.ry_origin - self.o) * s;
            d.rx_direction = self.d + (d.rx_direction - self.d) * s;
            d.ry_direction = self.d + (d.ry_direction - self.d) * s;
        }
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct RayDifferential {
    pub rx_origin: Point3f,
    pub ry_origin: Point3f,
    pub rx_direction: Vector3f,
    pub ry_direction: Vector3f,
}