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
/*
MIT License
Copyright (c) 2022 Christopher Collin Hall (aka DrPlantabyte)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//! # ZArray
//! Z-order indexed 2D and 3D arrays using Morton order (aka Z-order) with a convenient API for
//! common 2D and 3D access patterns. Use of zarray in place of a Vec of Vecs often improves
//! performance, especially for algorithms such as blurring and cellular automata.
//! ## About ZArray
//! The *zarray* crate is a lightweight Rust library that provides structs for working with 2D and
//! 3D arrays, using internal Z-Order Morton indexing to improve data localization for better
//! cache-line performance.
//! ## Quickstart Guide
//! Simply import *zarray::z2d::ZArray2D* and/or *zarray::z3d::ZArray3D* and then use the
//! *ZArray_D::new(...)* function to initialize a new instance. The type will automatically be
//! inferred from the povided default value. Note that only types which implement the *Copy* trait
//! are allowed (ie not Vec or other heap-allocating types).
//!
//! For example, here's a simple blur operation using ZArray2D, which generally performs better
//! than using a Vec of Vecs by about 10-25%:
//! ```rust
//! use zarray::z2d::ZArray2D;
//! let h: isize = 200;
//! let w: isize = 300;
//! let radius: isize = 3;
//! let mut src = ZArray2D::new(w as usize, h as usize, 0u8);
//! // set values
//! src.bounded_fill(100, 100, 200, 150, 255u8);
//! // sum neighbors values with ZArray
//! let mut blurred = ZArray2D::new(w as usize, h as usize, 0u16);
//! for y in 0..h { for x in 0..w {
//! let mut sum = 0;
//! for dy in -radius..radius+1 { for dx in -radius..radius+1 {
//! sum += *src.bounded_get(x+dx, y+dy).unwrap_or(&0u8) as u16;
//! } }
//! blurred.set(x as usize, y as usize, sum/((2*radius as u16+1).pow(2))).unwrap();
//! } }
//! ```
//!
//! ## How it works
//! the *ZArray_D* structs store data in 8x8 or 8x8x8 chuncks, using Z-order indexing to access the
//! data within each chunk (as described [here](https://en.wikipedia.org/wiki/Z-order_curve) ). In
//! so doing, the lowest 4 bits of each dimension are interdigitated to significantly improve data
//! locality and cache-line fetch efficiency (though not as much as a Hilbert curve would do)
//!
//! ## Why not just use Vec of Vecs (aka Vec<Vec<T>>)?
//! Most of the time, using a Vec<Vec<T>> would have great performance, so long as you remember to
//! structure your for-loops correctly. However, when the data is not accessed in a linear fashion,
//! such as when implementing a cellular automata or a blurring or ray tracing algorithm, then the
//! performance of a Vec<Vec<T>> can be significantly impaired by frequent RAM access and
//! cache-line misses. This is when data locality matters most for performance.
//!
//! ### Why not Z-Order the entire data array?
//! Two reasons: Firstly, Z-Order indexing only works on square/cube shaped data, so a pure Z-Order
//! index would waste huge amount of memory for 2D and 3D arrays that are long and thin. Second, on
//! most CPU architectures (Intel, AMD, and Arm), memory is accessed in 64-byte cache-lines, thus
//! the performance gains from Z-order indexing are less significant above 6 bits of linear
//! addressing space (ie 8x8 or 4x4x4)
//!
//! ## Note
//! Only types with the *Copy* trait can be stored in *ZArray_D* structs. Thus *zarray* works for
//! all numerical types and most simple data structs, but not for heap-allocating data types such
//! as Vec. This limitation arises from complexities in filling the data patches with initial
//! values. In addition, you would not see a performance improvement over a simple Vec<Vec<T>> if
//! the data resided on the heap.
//!
//! ## License
//! This library is provided under the MIT license. In other words: free to use as you wish.
//!
//! ## Contributing
//! If you'd like to contribute, go ahead and fork the GitHub repo and/or submit a pull request
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
/// This struct is an error type that is returned when attempting to get a value that is outside
/// the range of the data. It implements the Debug and Display traits so that it can be easily
/// printed as an error message.
pub struct LookUpError{
/// coordinate that was out of bounds
coord: Vec<usize>,
/// bounds of the ZArray*D that was violated
bounds: Vec<usize>,
}
impl Debug for LookUpError {
// programmer-facing error message
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
return write!(f, "{{ file: {}, line: {}, coord: {}, bounds: {} }}", file!(), line!(), vec_to_string(&self.coord), vec_to_string(&self.bounds));
}
}
impl Display for LookUpError {
// user-facing error message
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
return write!(f, "Error: could not access coordinate {} because it is out of range for size {}", vec_to_string(&self.coord), vec_to_string(&self.bounds));
}
}
impl Error for LookUpError{}
impl LookUpError {
}
/// Utility function for converting Vecs to Strings for the purpose of error reporting and debugging
fn vec_to_string(v: &Vec<usize>) -> String{
let mut sb = String::from("(");
let mut not_first = false;
for n in v {
if not_first {
sb += &String::from(", ");
} else {
not_first = true;
}
sb += &String::from(n.to_string());
}
sb += &String::from(")");
return sb;
}
/// This module is used for storing 2-dimensional data arrays, and internally uses Z-index arrays
/// to improve data localization and alignment to the CPU cache-line fetches. In other words, use
/// this to improve performance for 2D data that is randomly accessed rather than raster scanned
/// or if your data processing makes heavy use of neighbor look-up in both the X and Y directions.
/// # How It Works
/// When you initialize a zarray::z2d::ZArray2D struct, it creates an array of 8x8 data patches,
/// using Z-curve indexing within that patch. When you call a getter or setter method, it finds the
/// corresponding data patch and then looks up (or sets) the data from within the patch. Since the
/// cache-line size on most CPUs is 64 bytes (and up to only 128 bytes on more exotic chips), the
/// 8x8 patch is sufficient localization for the majority of applications.
/// # Example Usage
/// An example of a simple blurring operation
/// ```
/// use zarray::z2d::ZArray2D;
/// let w = 800;
/// let h = 600;
/// let mut input = ZArray2D::new(w, h, 0i32);
/// let mut blurred = ZArray2D::new(w, h, 0i32);
/// for y in 0..h {
/// for x in 0..w {
/// let random_number = (((x*1009+1031)*y*1013+1051) % 10) as i32;
/// input.set(x, y, random_number).unwrap();
/// }
/// }
/// let radius: i32 = 2;
/// for y in radius..h as i32-radius {
/// for x in radius..w as i32-radius {
/// let mut sum = 0;
/// for dy in -radius..radius+1 {
/// for dx in -radius..radius+1 {
/// sum += *input.bounded_get((x+dx) as isize, (y+dy) as isize).unwrap_or(&0);
/// }
/// }
/// blurred.set(x as usize, y as usize, sum/((2*radius+1).pow(2))).unwrap();
/// }
/// }
/// ```
pub mod z2d {
// Z-order indexing in 2 dimensions
use std::marker::PhantomData;
use crate::LookUpError;
/// Private struct for holding an 8x8 data patch
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct Patch<T> {
contents: [T; 64]
}
impl<T> Patch<T> {
/// data patch getter
/// # Parameters
/// * **x** - x coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **y** - y coord (only lowest 3 bits are used, rest of bits are ignored)
/// # Returns
/// Returns a reference to the value stored in the patch at location (x & 0x07), (y & 0x07)
fn get(&self, x: usize, y: usize) -> &T {
// 3-bit x 3-bit
return &self.contents[zorder_4bit_to_8bit(x as u8 & 0x07, y as u8 & 0x07) as usize];
}
/// data patch setter
/// # Parameters
/// * **x** - x coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **y** - y coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **new_val** - value to set
fn set(&mut self, x: usize, y: usize, new_val: T) {
// 3-bit x 3-bit
let i = zorder_4bit_to_8bit(x as u8 & 0x07, y as u8 & 0x07) as usize;
//let old_val = &self.contents[i];
self.contents[i] = new_val;
//return old_val;
}
}
/// function for converting coordinate to index of data patch in the array of patches
fn patch_index(x: usize, y: usize, pwidth: usize) -> usize {
return (x >> 3) + ((y >> 3) * (pwidth));
}
/// This is primary struct for z-indexed 2D arrays. Create new instances with
/// ZArray2D::new(x_size, y_size, initial_value)
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ZArray2D<T> {
// for heap allocated data
width: usize,
height: usize,
pwidth: usize,
patches: Vec<Patch<T>>,
_phantomdata: PhantomData<T>,
}
impl<T> ZArray2D<T> where T: Copy {
/// Create a Z-index 2D array of values, initially filled with the provided default value
/// # Parameters
/// * **width** - size of this 2D array in the X dimension
/// * **height** - size of this 2D array in the Y dimension
/// * **default_val** - initial fill value (if a struct type, then it must implement the
/// Copy trait)
/// # Returns
/// Returns an initialized *ZArray2D* struct filled with *default_val*
pub fn new(width: usize, height: usize, default_val: T) -> ZArray2D<T> {
let pwidth = ((width-1) >> 3) + 1;
let pheight = ((height-1) >> 3) + 1;
let patch_count = pwidth * pheight;
let mut p = Vec::with_capacity(patch_count);
for _ in 0..patch_count {
p.push(Patch { contents: [default_val; 64] });
}
return ZArray2D { width, height, pwidth, patches: p, _phantomdata: PhantomData };
}
/// Gets the (x, y) size of this 2D array
/// # Returns
/// Returns a tuple of (width, height) for this 2D array
pub fn dimensions(&self) -> (usize, usize) {
return (self.width, self.height);
}
/// Gets the X-dimension size (aka width) of this 2D array
/// # Returns
/// Returns the size in the X dimension
pub fn xsize(&self) -> usize {
return self.width;
}
/// Alias for `xsize()`
/// # Returns
/// Returns the size in the X dimension
pub fn width(&self) -> usize {
return self.xsize();
}
/// Gets the Y-dimension size (aka height) of this 2D array
/// # Returns
/// Returns the size in the Y dimension
pub fn ysize(&self) -> usize {
return self.height;
}
/// Alias for `ysize()`
/// # Returns
/// Returns the size in the Y dimension
pub fn height(&self) -> usize {
return self.ysize();
}
/// Gets a value from the 2D array, or returns a *LookUpError* if the provided coordinate
/// is out of bounds. If you are using a default value for out-of-bounds coordinates,
/// then you should use the *bounded_get(x, y)* method instead. If you want access to
/// wrap-around (eg (-2, 0) equivalent to (width-2,0)), then use the *wrapped_get(x, y)*
/// method.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// # Returns
/// Returns a Result type that holds either the returned data value (as a reference) from
/// the 2D array, or a *LookUpError* signalling that the coordinate is out of bounds
pub fn get(&self, x: usize, y: usize) -> Result<&T, LookUpError> {
if x < self.width && y < self.height {
Ok(self.patches[patch_index(x, y, self.pwidth)].get(x, y))
} else {
Err(LookUpError { coord: vec![x, y], bounds: vec![self.width, self.height] })
}
}
/// Sets a value in the 2D array, or returns a *LookUpError* if the provided coordinate
/// is out of bounds. If you want out-of-bound coordinates to result in a no-op, then use
/// the *bounded_set(x, y, val)* method instead. If you want access to wrap-around (eg
/// (-2, 0) equivalent to (width-2,0)), then use the *wrapped_set(x, y, val)* method.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **new_val** - value to store in the 2D array at (x, y)
/// # Returns
/// Returns a Result type that is either empty or a *LookUpError* signalling that the
/// coordinate is out of bounds
pub fn set(&mut self, x: usize, y: usize, new_val: T) -> Result<(), LookUpError> {
if x < self.width && y < self.height {
Ok(self.patches[patch_index(x, y, self.pwidth)].set(x, y, new_val))
} else {
Err(LookUpError { coord: vec![x, y], bounds: vec![self.width, self.height] })
}
}
/// Gets a value from the 2D array without bounds checking
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// # Returns
/// Returns a data value (as a reference) from the 2D array
pub fn get_unchecked(&self, x: usize, y: usize) -> &T {
return self.patches[patch_index(x, y, self.pwidth)].get(x, y);
}
/// Sets a value in the 2D array without bounds checking
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **new_val** - value to store in the 2D array at (x, y)
pub fn set_unchecked(&mut self, x: usize, y: usize, new_val: T) {
self.patches[patch_index(x, y, self.pwidth)].set(x, y, new_val);
}
/// Gets a value from the 2D array, wrapping around the X and Y axese when the coordinates
/// are negative or outside the size of this 2D array. Good for when you want tiling
/// behavior.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// # Returns
/// Returns a reference to the data stored at the provided coordinate (wrapping both x
/// and y dimensions)
pub fn wrapped_get(&self, x: isize, y: isize) -> &T {
let x = (self.width as isize + (x % self.width as isize)) as usize % self.width;
let y = (self.height as isize + (y % self.height as isize)) as usize % self.height;
return &self.patches[patch_index(x, y, self.pwidth)].get(x, y);
}
/// Sets a value in the 2D array at the provided coordinate, wrapping the X and Y axese
/// if the coordinate is negative or out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **new_val** - value to store in the 2D array at (x, y), wrapping around both the x
/// and y dimensions
pub fn wrapped_set(&mut self, x: isize, y: isize, new_val: T) {
let x = (self.width as isize + (x % self.width as isize)) as usize % self.width;
let y = (self.height as isize + (y % self.height as isize)) as usize % self.height;
self.patches[patch_index(x, y, self.pwidth)].set(x, y, new_val);
}
/// Gets a value from the 2D array as an Option that is None if the coordinate
/// is out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// # Returns
/// Returns an Option type that holds either the returned data value (as a reference) from
/// the 2D array, or *None* signalling that the coordinate is out of bounds (which can be
/// combined with .unwrap_or(default_value) to implement an out-of-bounds default)
pub fn bounded_get(&self, x: isize, y: isize) -> Option<&T> {
if x >= 0 && y >= 0 && x < self.width as isize && y < self.height as isize {
return Some(&self.patches[patch_index(x as usize, y as usize, self.pwidth)]
.get(x as usize, y as usize));
} else {
return None;
}
}
/// Sets a value in the 2D array if and only if the provided coordinate is in bounds.
/// Otherwise this method does nothing if the coordiante is out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **new_val** - value to store int eh 2D array at (x, y)
pub fn bounded_set(&mut self, x: isize, y: isize, new_val: T) {
if x >= 0 && y >= 0 && x < self.width as isize && y < self.height as isize {
self.patches[patch_index(x as usize, y as usize, self.pwidth)]
.set(x as usize, y as usize, new_val);
} else {
// no-op
}
}
/// Fills a region of this 2D array with a given value, or returns a *LookUpError* if the
/// provided coordinates go out of bounds. If you just want to ignore any
/// out-of-bounds coordinates, then you should use the *bounded_fill(x1, y1, x2, y2)*
/// method instead. If you want access to wrap-around (eg (-2, 0) equivalent to
/// (width-2,0)), then use the *wrapped_fill(x, y)* method.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **new_val** - value to store in the 2D array in the bounding box defined by
/// (x1, y1) -> (x2, y2)
/// # Returns
/// Returns a Result type that is either empty or a *LookUpError* signalling that a
/// coordinate is out of bounds
pub fn fill(&mut self, x1: usize, y1: usize, x2: usize, y2: usize, new_val: T)
-> Result<(), LookUpError> {
for y in y1..y2 {
for x in x1..x2 {
self.set(x, y, new_val)?;
}
}
Ok(())
}
/// Fills a region of this 2D array with a given value, wrapping the axese when
/// coordinates go out of bounds.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **new_val** - value to store in the 2D array in the bounding box defined by
/// (x1, y1) -> (x2, y2) with wrapped axese
pub fn wrapped_fill(&mut self, x1: isize, y1: isize, x2: isize, y2: isize, new_val: T) {
for y in y1..y2 {
for x in x1..x2 {
self.wrapped_set(x, y, new_val);
}
}
}
/// Fills a region of this 2D array with a given value, ignoring any
/// coordinates that go out of bounds.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **new_val** - value to store in the 2D array in the bounding box defined by
/// (x1, y1) -> (x2, y2)
pub fn bounded_fill(&mut self, x1: isize, y1: isize, x2: isize, y2: isize, new_val: T) {
for y in y1..y2 {
for x in x1..x2 {
self.bounded_set(x, y, new_val);
}
}
}
/// Creates an iterator that iterates through the 2D array in Z-order
/// # Returns
/// A new ZArray2DIterator instance
pub fn iter(&self) -> ZArray2DIterator<T> {
ZArray2DIterator::new(self)
}
}
#[test]
fn check_patch_count_2d() {
let arr = ZArray2D::new(1, 1, 0u8);
assert_eq!(arr.patches.len(), 1, "Allocated wrong number of patches for array of size {}x{}", arr.width, arr.height);
let arr = ZArray2D::new(8, 8, 0u8);
assert_eq!(arr.patches.len(), 1, "Allocated wrong number of patches for array of size {}x{}", arr.width, arr.height);
let arr = ZArray2D::new(9, 8, 0u8);
assert_eq!(arr.patches.len(), 2, "Allocated wrong number of patches for array of size {}x{}", arr.width, arr.height);
let arr = ZArray2D::new(8, 9, 0u8);
assert_eq!(arr.patches.len(), 2, "Allocated wrong number of patches for array of size {}x{}", arr.width, arr.height);
let arr = ZArray2D::new(9, 9, 0u8);
assert_eq!(arr.patches.len(), 4, "Allocated wrong number of patches for array of size {}x{}", arr.width, arr.height);
}
/// This struct is used by `ZArray2DIterator` to present values to the consumer of the
/// iterator
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ZArray2DIteratorItem <T> {
/// x-dimension coordinate
pub x: usize,
/// y-dimension coordinate
pub y: usize,
/// value at this coordinate
pub value: T
}
/// private state management enum
enum IterState {
Start, Processing, Done
}
/// Iterator that iterates through the array
pub struct ZArray2DIterator<'a, T: Copy> {
/// array to iterate over
array: &'a ZArray2D<T>,
patch: usize,
index: usize,
state: IterState
}
impl<'a, T: Copy> ZArray2DIterator<'a, T> {
fn new(array: &'a ZArray2D<T>) -> ZArray2DIterator<'a, T> {
if array.width == 0 || array.height == 0 {
ZArray2DIterator{array, patch: 0, index: 0, state: IterState::Done} // make a "done" iterator for empty arrays
} else {
ZArray2DIterator{array, patch: 0, index: 0, state: IterState::Start}
}
}
}
impl<'a, T: Copy> Iterator for ZArray2DIterator<'a, T> {
type Item = ZArray2DIteratorItem<T>;
fn next(&mut self) -> Option<Self::Item> {
match &self.state {
IterState::Done=> None,
IterState::Start=> {
self.state = IterState::Processing;
Some(ZArray2DIteratorItem{x: 0, y: 0, value: self.array.patches[0].contents[0]})
},
IterState::Processing => {
let mut x ; let mut y ;
loop {
self.index += 1;
if self.index >= 64 {
self.index = 0;
self.patch += 1;
}
let yx_lower_pits = REVERSE_ZLUT[self.index];
x = ((self.patch % self.array.pwidth) << 3) | (yx_lower_pits & 0x07) as usize;
y = ((self.patch / self.array.pwidth) << 3) | ((yx_lower_pits >> 3) & 0x07) as usize;
if x < self.array.width && y < self.array.height{
break;
}
if self.patch >= self.array.patches.len() {
self.state = IterState::Done;
return None;
}
}
Some(ZArray2DIteratorItem{x, y, value: self.array.patches[self.patch].contents[self.index]})
}
}
}
}
/// Used for Z-index look-up
static ZLUT: [u8; 16] = [
0b00000000,
0b00000001,
0b00000100,
0b00000101,
0b00010000,
0b00010001,
0b00010100,
0b00010101,
0b01000000,
0b01000001,
0b01000100,
0b01000101,
0b01010000,
0b01010001,
0b01010100,
0b01010101
];
/// used by iterators for fast conversion from internal index to X, Y. Each number is 0byyyxxx
static REVERSE_ZLUT: [u8; 64] = [
0 , 1, 8, 9, 2, 3, 10, 11, 16, 17, 24, 25, 18, 19, 26, 27,
4 , 5, 12, 13, 6, 7, 14, 15, 20, 21, 28, 29, 22, 23, 30, 31,
32, 33, 40, 41, 34, 35, 42, 43, 48, 49, 56, 57, 50, 51, 58, 59,
36, 37, 44, 45, 38, 39, 46, 47, 52, 53, 60, 61, 54, 55, 62, 63
];
/// General purpose Z-index function to convert a two-dimensional coordinate into a localized
/// one-dimensional coordinate
/// # Parameters
/// * **x** - x dimension coordinate *(ONLY THE LOWER 4 BITS WILL BE USED!)*
/// * **y** - y dimension coordinate *(ONLY THE LOWER 4 BITS WILL BE USED!)*
/// # Returns
/// Z-curve index for use as an index in a linear array meant to hold 2D data. In other words,
/// given the binary numbers X=0b0000xxxx and Y=0b0000yyyy, this method will return 0byxyxyxyx.
pub fn zorder_4bit_to_8bit(x: u8, y: u8) -> u8 {
let x_bits = ZLUT[(x & 0x0F) as usize];
let y_bits = ZLUT[(y & 0x0F) as usize] << 1;
return y_bits | x_bits;
}
/// General purpose Z-index function to convert a two-dimensional coordinate into a localized
/// one-dimensional coordinate
/// # Parameters
/// * **x** - x dimension coordinate (8 bits)
/// * **y** - y dimension coordinate (8 bits)
/// # Returns
/// Z-curve index for use as an index in a linear array meant to hold 2D data. In other words,
/// given the binary numbers Y=0b0000xxxx and Y=0b0000yyyy, this method will return 0byxyxyxyx.
pub fn zorder_8bit_to_16bit(x:u8, y:u8) -> u16 {
return ((zorder_4bit_to_8bit(x >> 4, y >> 4) as u16) << 8) | zorder_4bit_to_8bit(x, y) as u16
}
/// General purpose Z-index function to convert a two-dimensional coordinate into a localized
/// one-dimensional coordinate
/// # Parameters
/// * **x** - x dimension coordinate (16 bits)
/// * **y** - y dimension coordinate (16 bits)
/// # Returns
/// Z-curve index for use as an index in a linear array meant to hold 2D data. In other words,
/// given the binary numbers Y=0b0000xxxx and Y=0b0000yyyy, this method will return 0byxyxyxyx.
pub fn zorder_16bit_to_32bit(x:u16, y:u16) -> u32 {
return ((zorder_8bit_to_16bit((x & 0xFF) as u8, (y & 0xFF) as u8) as u32) << 16) | zorder_8bit_to_16bit((x >> 8) as u8, (y >> 8) as u8) as u32
}
}
/// This module is used for storing 3-dimensional data arrays, and internally uses Z-index arrays
/// to improve data localization and alignment to the CPU cache-line fetches. In other words, use
/// this to improve performance for 3D data that is randomly accessed rather than raster scanned
/// or if your data processing makes heavy use of neighbor look-up in the X, Y, and Z directions.
/// # How It Works
/// When you initialize a zarray::z3d::ZArray3D struct, it creates an array of 8x8x8 data patches
/// (512 total elements per patch), using Z-curve indexing within that patch. When you call a
/// getter or setter method, it finds the corresponding data patch and then looks up (or sets) the
/// data from within the patch.
/// # Example Usage
/// The following example could be used as part of an erosion simulation:
/// ```
/// use zarray::z3d::ZArray3D;
/// let width = 100;
/// let length = 200;
/// let depth = 25;
/// let air = 0f32;
/// let soil_hardness = 1f32;
/// let rock_hardness = 8f32;
/// let drip_power = 1.5f32;
/// let iterations = 12;
/// let mut map = ZArray3D::new(width, length, depth, air);
/// map.fill(0,0,5, width,length,depth, soil_hardness).unwrap();
/// map.fill(0,0,15, width,length,depth, rock_hardness).unwrap();
/// for boulder in [(34,88,6), (66,122,9), (11,154,5), (35,93,8), (72,75,12)]{
/// map.set(boulder.0, boulder.1, boulder.2, rock_hardness).unwrap();
/// }
/// for _ in 0..iterations{
/// for x in 0..width{for y in 0..length{
/// let mut drip = drip_power;
/// let mut z = 0;
/// while drip > 0f32 {
/// let h = *map.bounded_get(x as isize, y as isize, z).unwrap_or(&100f32);
/// if h > drip {
/// map.bounded_set(x as isize, y as isize, z, h - drip);
/// drip = 0.;
/// } else {
/// map.bounded_set(x as isize, y as isize, z, 0.);
/// drip -= h;
/// }
/// z += 1;
/// }
/// }}
/// }
/// ```
pub mod z3d {
// Z-order indexing in 2 dimensions
use std::marker::PhantomData;
use crate::LookUpError;
/// Private struct for holding an 8x8x8 data patch
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct Patch<T>{
contents: [T;512]
}
impl<T> Patch<T> {
/// data patch getter
/// # Parameters
/// * **x** - x coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **y** - y coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **z** - z coord (only lowest 3 bits are used, rest of bits are ignored)
/// # Returns
/// Returns a reference to the value stored in the patch at location (x, y, z) (lowest 3
/// bits only)
fn get(&self, x: usize, y:usize, z:usize) -> &T {
// 3-bit x 3-bit x 3-bit
return &self.contents[zorder_4bit_to_12bit(
x as u8 & 0x07, y as u8 & 0x07, z as u8 & 0x07) as usize];
}
/// data patch setter
/// # Parameters
/// * **x** - x coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **y** - y coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **z** - z coord (only lowest 3 bits are used, rest of bits are ignored)
/// * **new_val** - value to set at (x,y,z)
fn set(&mut self, x: usize, y:usize, z:usize, new_val: T) {
// 3-bit x 3-bit
let i = zorder_4bit_to_12bit(
x as u8 & 0x07, y as u8 & 0x07, z as u8 & 0x07) as usize;
self.contents[i] = new_val;
}
}
/// function for converting coordinate to index of data patch in the array of patches
fn patch_index(x: usize, y:usize, z:usize, pxsize: usize, pysize: usize) -> usize{
return (x >> 3) + pxsize * ((y >> 3) + (pysize * (z >> 3)));
}
/// This is primary struct for z-indexed 3D arrays. Create new instances with
/// ZArray3D::new(x_size, y_size, z_size, initial_value)
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ZArray3D<T> {
// for heap allocated data
xsize: usize,
ysize: usize,
zsize: usize,
pxsize: usize,
pysize: usize,
patches: Vec<Patch<T>>,
_phantomdata: PhantomData<T>,
}
impl<T> ZArray3D<T> where T: Copy {
/// Create a Z-index 3D array of values, initially filled with the provided default value
/// # Parameters
/// * **xsize** - size of this 3D array in the X dimension
/// * **ysize** - size of this 3D array in the Y dimension
/// * **zsize** - size of this 3D array in the Z dimension
/// * **default_val** - initial fill value (if a struct type, then it must implement the
/// Copy trait)
/// # Returns
/// Returns an initialized *ZArray3D* struct filled with *default_val*
pub fn new(xsize: usize, ysize: usize, zsize: usize, default_val: T) -> ZArray3D<T>{
let px = ((xsize-1) >> 3) + 1;
let py = ((ysize-1) >> 3) + 1;
let pz = ((zsize-1) >> 3) + 1;
let patch_count = px * py * pz;
let mut p = Vec::with_capacity(patch_count);
for _ in 0..patch_count{
p.push(Patch{contents: [default_val; 512]});
}
return ZArray3D { xsize, ysize, zsize, pxsize: px, pysize: py,
patches: p, _phantomdata: PhantomData};
}
/// Gets the (x, y, z) size of this 3D array
/// # Returns
/// Returns a tuple of (width, height, depth) for this 2D array
pub fn dimensions(&self) -> (usize, usize, usize){
return (self.xsize, self.ysize, self.zsize);
}
/// Gets the X-dimension size (aka width) of this 3D array
/// # Returns
/// Returns the size in the X dimension
pub fn xsize(&self) -> usize {
return self.xsize;
}
/// Alias for `xsize()`
/// # Returns
/// Returns the size in the X dimension
pub fn width(&self) -> usize {
return self.xsize();
}
/// Gets the Y-dimension size (aka height) of this 3D array
/// # Returns
/// Returns the size in the Y dimension
pub fn ysize(&self) -> usize {
return self.ysize;
}
/// Alias for `ysize()`
/// # Returns
/// Returns the size in the Y dimension
pub fn height(&self) -> usize {
return self.ysize();
}
/// Gets the Z-dimension size (aka depth) of this 3D array
/// # Returns
/// Returns the size in the Z dimension
pub fn zsize(&self) -> usize {
return self.zsize;
}
/// Alias for `zsize()`
/// # Returns
/// Returns the size in the Z dimension
pub fn depth(&self) -> usize {
return self.zsize();
}
/// Gets a value from the 3D array, or returns a *LookUpError* if the provided coordinate
/// is out of bounds. If you are using a default value for out-of-bounds coordinates,
/// then you should use the *bounded_get(x, y, z)* method instead. If you want access to
/// wrap-around (eg (-2, 0, 1) equivalent to (width-2, 0, 1)), then use the
/// *wrapped_get(x, y, z)* method.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// # Returns
/// Returns a Result type that holds either the returned data value (as a reference) from
/// the 3D array, or a *LookUpError* signalling that the coordinate is out of bounds
pub fn get(&self, x: usize, y: usize, z: usize) -> Result<&T,LookUpError>{
if x < self.xsize && y < self.ysize && z < self.zsize {
Ok(self.patches[patch_index(x, y, z, self.pxsize, self.pysize)].get(x, y, z))
} else {
Err(LookUpError{coord: vec![x, y, z],
bounds: vec![self.xsize, self.ysize, self.zsize]})
}
}
/// Sets a value in the 3D array, or returns a *LookUpError* if the provided coordinate
/// is out of bounds. If you want out-of-bound coordinates to result in a no-op, then use
/// the *bounded_set(x, y, z, val)* method instead. If you want access to wrap-around (eg
/// (-2, 0, 1) equivalent to (width-2, 0, 1)), then use the
/// *wrapped_set(x, y, z, val)* method.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// * **new_val** - value to store in the 3D array at (x, y, z)
/// # Returns
/// Returns a Result type that is either empty or a *LookUpError* signalling that the
/// coordinate is out of bounds
pub fn set(&mut self, x: usize, y: usize, z: usize, new_val: T) -> Result<(),LookUpError>{
if x < self.xsize && y < self.ysize && z < self.zsize {
Ok(self.patches[patch_index(x, y, z, self.pxsize, self.pysize)]
.set(x, y, z, new_val))
} else {
Err(LookUpError{coord: vec![x, y, z],
bounds: vec![self.xsize, self.ysize, self.zsize]})
}
}
/// Gets a value from the 3D array without bounds checking
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// # Returns
/// Returns the data value (as a reference) from the 3D array
pub fn get_unchecked(&self, x: usize, y: usize, z: usize) -> &T {
return self.patches[patch_index(x, y, z, self.pxsize, self.pysize)].get(x, y, z);
}
/// Sets a value in the 3D array without bounds checking
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// * **new_val** - value to store in the 3D array at (x, y, z)
pub fn set_unchecked(&mut self, x: usize, y: usize, z: usize, new_val: T) {
self.patches[patch_index(x, y, z, self.pxsize, self.pysize)]
.set(x, y, z, new_val);
}
/// Gets a value from the 3D array, wrapping around the X and Y axese when the coordinates
/// are negative or outside the size of this 2D array. Good for when you want tiling
/// behavior.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// # Returns
/// Returns a reference to the data stored at the provided coordinate (wrapping both x
/// and y dimensions)
pub fn wrapped_get(&self, x: isize, y: isize, z: isize) -> &T{
let x = (self.xsize as isize + (x % self.xsize as isize)) as usize % self.xsize;
let y = (self.ysize as isize + (y % self.ysize as isize)) as usize % self.ysize;
let z = (self.zsize as isize + (z % self.zsize as isize)) as usize % self.zsize;
return &self.patches[patch_index(x, y, z, self.pxsize, self.pysize)].get(x, y, z);
}
/// Sets a value in the 3D array at the provided coordinate, wrapping the X, Y, and Z axese
/// if the coordinate is negative or out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// * **new_val** - value to store in the 3D array at (x, y, z), wrapping around
/// the x, y, and z dimensions
pub fn wrapped_set(&mut self, x: isize, y: isize, z: isize, new_val: T) {
let x = (self.xsize as isize + (x % self.xsize as isize)) as usize % self.xsize;
let y = (self.ysize as isize + (y % self.ysize as isize)) as usize % self.ysize;
let z = (self.zsize as isize + (z % self.zsize as isize)) as usize % self.zsize;
self.patches[patch_index(x, y, z, self.pxsize, self.pysize)].set(x, y, z, new_val);
}
/// Gets a value from the 3D array as an Option that is None if the coordinate
/// is out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// # Returns
/// Returns an Option type that holds either the returned data value (as a reference) from
/// the 3D array, or *None* signalling that the coordinate is out of bounds (which can be
/// combined with .unwrap_or(default_value) to implement an out-of-bounds default)
pub fn bounded_get(&self, x: isize, y: isize, z: isize) -> Option<&T>{
if x >= 0 && y >= 0 && z >= 0
&& x < self.xsize as isize && y < self.ysize as isize && z < self.zsize as isize {
return Some(&self.patches[
patch_index(x as usize, y as usize, z as usize, self.pxsize, self.pysize)]
.get(x as usize, y as usize, z as usize));
} else {
return None;
}
}
/// Sets a value in the 3D array if and only if the provided coordinate is in bounds.
/// Otherwise this method does nothing if the coordinate is out of bounds.
/// # Parameters
/// * **x** - x dimension coordinate
/// * **y** - y dimension coordinate
/// * **z** - z dimension coordinate
/// * **new_val** - value to store int eh zD array at (x, y, z)
pub fn bounded_set(&mut self, x: isize, y: isize, z: isize, new_val: T) {
if x >= 0 && y >= 0 && z >= 0
&& x < self.xsize as isize && y < self.ysize as isize && z < self.zsize as isize {
self.patches[
patch_index(x as usize, y as usize, z as usize, self.pxsize, self.pysize)]
.set(x as usize, y as usize, z as usize, new_val);
} else {
// no-op
}
}
/// Fills a region of this 3D array with a given value, or returns a *LookUpError* if the
/// provided coordinates go out of bounds. If you just want to ignore any
/// out-of-bounds coordinates, then you should use the
/// *bounded_fill(x1, y1, z1, x2, y2, z2)*
/// method instead. If you want access to wrap-around (eg (-2, 0, 1) equivalent to
/// (width-2, 0, 1)), then use the *wrapped_fill(x, y, z)* method.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **z1** - the first z dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **z2** - the second z dimension coordinate (exclusive)
/// * **new_val** - value to store in the 2D array in the bounding box defined by
/// (x1, y1, z1) -> (x2, y2, z2)
/// # Returns
/// Returns a Result type that is either empty or a *LookUpError* signalling that a
/// coordinate is out of bounds
pub fn fill(&mut self, x1: usize, y1: usize, z1: usize, x2: usize, y2: usize, z2: usize,
new_val: T)
-> Result<(), LookUpError> {
for y in y1..y2{ for x in x1..x2{ for z in z1..z2{
self.set(x, y, z, new_val)?;
} } }
Ok(())
}
/// Fills a region of this 3D array with a given value, wrapping the axese when
/// coordinates go out of bounds.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **z1** - the first z dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **z2** - the second z dimension coordinate (exclusive)
/// * **new_val** - value to store in the 3D array in the bounding box defined by
/// (x1, y1, z1) -> (x2, y2, z2)
pub fn wrapped_fill(&mut self, x1: isize, y1: isize, z1: isize,
x2: isize, y2: isize, z2: isize, new_val: T) {
for y in y1..y2{ for x in x1..x2{ for z in z1..z2{
self.wrapped_set(x, y, z, new_val);
} } }
}
/// Fills a region of this 3D array with a given value, ignoring any
/// coordinates that go out of bounds.
/// # Parameters
/// * **x1** - the first x dimension coordinate (inclusive)
/// * **y1** - the first y dimension coordinate (inclusive)
/// * **z1** - the first z dimension coordinate (inclusive)
/// * **x2** - the second x dimension coordinate (exclusive)
/// * **y2** - the second y dimension coordinate (exclusive)
/// * **z2** - the second z dimension coordinate (exclusive)
/// * **new_val** - value to store in the 3D array in the bounding box defined by
/// (x1, y1, z1) -> (x2, y2, z2)
pub fn bounded_fill(&mut self, x1: isize, y1: isize, z1: isize,
x2: isize, y2: isize, z2: isize, new_val: T) {
for y in y1..y2{ for x in x1..x2{ for z in z1..z2{
self.bounded_set(x, y, z, new_val);
} } }
}
/// Creates an iterator that iterates through the 3D array in Z-order
/// # Returns
/// A new ZArray3DIterator instance
pub fn iter(&self) -> ZArray3DIterator<T> {
ZArray3DIterator::new(self)
}
}
#[test]
fn check_patch_count_3d() {
let arr = ZArray3D::new(1, 1, 1, 0u8);
assert_eq!(arr.patches.len(), 1, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
let arr = ZArray3D::new(8, 8, 8, 0u8);
assert_eq!(arr.patches.len(), 1, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
let arr = ZArray3D::new(9, 8, 8, 0u8);
assert_eq!(arr.patches.len(), 2, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
let arr = ZArray3D::new(8, 9, 8, 0u8);
assert_eq!(arr.patches.len(), 2, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
let arr = ZArray3D::new(8, 8, 9, 0u8);
assert_eq!(arr.patches.len(), 2, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
let arr = ZArray3D::new(9, 9, 9, 0u8);
assert_eq!(arr.patches.len(), 8, "Allocated wrong number of patches for array of size {}x{}x{}", arr.xsize, arr.ysize, arr.zsize);
}
/// Used for converting 3D coords to linear Z-index
static ZLUT: [u16; 16] = [
0b0000000000000000,
0b0000000000000001,
0b0000000000001000,
0b0000000000001001,
0b0000000001000000,
0b0000000001000001,
0b0000000001001000,
0b0000000001001001,
0b0000001000000000,
0b0000001000000001,
0b0000001000001000,
0b0000001000001001,
0b0000001001000000,
0b0000001001000001,
0b0000001001001000,
0b0000001001001001
];
/// General purpose Z-index function to convert a three-dimensional coordinate into a localized
/// one-dimensional coordinate
/// # Parameters
/// * **x** - x dimension coordinate *(ONLY THE LOWER 4 BITS WILL BE USED!)*
/// * **y** - y dimension coordinate *(ONLY THE LOWER 4 BITS WILL BE USED!)*
/// * **z** - z dimension coordinate *(ONLY THE LOWER 4 BITS WILL BE USED!)*
/// # Returns
/// Z-curve index for use as an index in a linear array meant to hold 2D data. In other words,
/// given the binary numbers X=0b0000xxxx, Y=0b0000yyyy, and Z=0b0000zzzz, then this method
/// will return 0b0000zyxzyxzyxzyx.
pub fn zorder_4bit_to_12bit(x: u8, y: u8, z: u8) -> u16 {
let x_bits = ZLUT[(x & 0x0F) as usize];
let y_bits = ZLUT[(y & 0x0F) as usize] << 1;
let z_bits = ZLUT[(z & 0x0F) as usize] << 2;
return z_bits | y_bits | x_bits;
}
/// General purpose Z-index function to convert a three-dimensional coordinate into a localized
/// one-dimensional coordinate
/// # Parameters
/// * **x** - x dimension coordinate (8 bit)
/// * **y** - y dimension coordinate (8 bit)
/// * **z** - z dimension coordinate (8 bit)
/// # Returns
/// Z-curve index for use as an index in a linear array meant to hold 2D data. In other words,
/// given the binary numbers X=0b0000xxxx, Y=0b0000yyyy, and Z=0b0000zzzz, then this method
/// will return 0b0000zyxzyxzyxzyx.
pub fn zorder_8bit_to_24bit(x:u8, y:u8, z: u8) -> u32 {
return ((zorder_4bit_to_12bit(x >> 4, y >> 4, z >> 4) as u32) << 12)
| zorder_4bit_to_12bit(x, y, z) as u32
}
/// Used by iterators to back-calculate the XYZ of an index, bit order is 0bzzzyyyxxx
static REVERSE_ZLUT: [u16; 512] = [
0, 1, 8, 9, 64, 65, 72, 73, 2, 3, 10, 11, 66, 67, 74, 75,
16, 17, 24, 25, 80, 81, 88, 89, 18, 19, 26, 27, 82, 83, 90, 91,
128, 129, 136, 137, 192, 193, 200, 201, 130, 131, 138, 139, 194, 195, 202, 203,
144, 145, 152, 153, 208, 209, 216, 217, 146, 147, 154, 155, 210, 211, 218, 219,
4, 5, 12, 13, 68, 69, 76, 77, 6, 7, 14, 15, 70, 71, 78, 79,
20, 21, 28, 29, 84, 85, 92, 93, 22, 23, 30, 31, 86, 87, 94, 95,
132, 133, 140, 141, 196, 197, 204, 205, 134, 135, 142, 143, 198, 199, 206, 207,
148, 149, 156, 157, 212, 213, 220, 221, 150, 151, 158, 159, 214, 215, 222, 223,
32, 33, 40, 41, 96, 97, 104, 105, 34, 35, 42, 43, 98, 99, 106, 107,
48, 49, 56, 57, 112, 113, 120, 121, 50, 51, 58, 59, 114, 115, 122, 123,
160, 161, 168, 169, 224, 225, 232, 233, 162, 163, 170, 171, 226, 227, 234, 235,
176, 177, 184, 185, 240, 241, 248, 249, 178, 179, 186, 187, 242, 243, 250, 251,
36, 37, 44, 45, 100, 101, 108, 109, 38, 39, 46, 47, 102, 103, 110, 111,
52, 53, 60, 61, 116, 117, 124, 125, 54, 55, 62, 63, 118, 119, 126, 127,
164, 165, 172, 173, 228, 229, 236, 237, 166, 167, 174, 175, 230, 231, 238, 239,
180, 181, 188, 189, 244, 245, 252, 253, 182, 183, 190, 191, 246, 247, 254, 255,
256, 257, 264, 265, 320, 321, 328, 329, 258, 259, 266, 267, 322, 323, 330, 331,
272, 273, 280, 281, 336, 337, 344, 345, 274, 275, 282, 283, 338, 339, 346, 347,
384, 385, 392, 393, 448, 449, 456, 457, 386, 387, 394, 395, 450, 451, 458, 459,
400, 401, 408, 409, 464, 465, 472, 473, 402, 403, 410, 411, 466, 467, 474, 475,
260, 261, 268, 269, 324, 325, 332, 333, 262, 263, 270, 271, 326, 327, 334, 335,
276, 277, 284, 285, 340, 341, 348, 349, 278, 279, 286, 287, 342, 343, 350, 351,
388, 389, 396, 397, 452, 453, 460, 461, 390, 391, 398, 399, 454, 455, 462, 463,
404, 405, 412, 413, 468, 469, 476, 477, 406, 407, 414, 415, 470, 471, 478, 479,
288, 289, 296, 297, 352, 353, 360, 361, 290, 291, 298, 299, 354, 355, 362, 363,
304, 305, 312, 313, 368, 369, 376, 377, 306, 307, 314, 315, 370, 371, 378, 379,
416, 417, 424, 425, 480, 481, 488, 489, 418, 419, 426, 427, 482, 483, 490, 491,
432, 433, 440, 441, 496, 497, 504, 505, 434, 435, 442, 443, 498, 499, 506, 507,
292, 293, 300, 301, 356, 357, 364, 365, 294, 295, 302, 303, 358, 359, 366, 367,
308, 309, 316, 317, 372, 373, 380, 381, 310, 311, 318, 319, 374, 375, 382, 383,
420, 421, 428, 429, 484, 485, 492, 493, 422, 423, 430, 431, 486, 487, 494, 495,
436, 437, 444, 445, 500, 501, 508, 509, 438, 439, 446, 447, 502, 503, 510, 511,
];
/// This struct is used by `ZArray2DIterator` to present values to the consumer of the
/// iterator
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ZArray3DIteratorItem <T> {
/// x-dimension coordinate
pub x: usize,
/// y-dimension coordinate
pub y: usize,
/// z-dimension coordinate
pub z: usize,
/// value at this coordinate
pub value: T
}
/// private state management enum
enum IterState {
Start, Processing, Done
}
/// Iterator that iterates through the array
pub struct ZArray3DIterator<'a, T: Copy> {
/// array to iterate over
array: &'a ZArray3D<T>,
patch: usize,
index: usize,
state: IterState
}
impl<'a, T: Copy> ZArray3DIterator<'a, T> {
fn new(array: &'a ZArray3D<T>) -> ZArray3DIterator<'a, T> {
if array.xsize == 0 || array.ysize == 0 || array.zsize == 0 {
ZArray3DIterator{array, patch: 0, index: 0, state: IterState::Done} // make a "done" iterator for empty arrays
} else {
ZArray3DIterator{array, patch: 0, index: 0, state: IterState::Start}
}
}
}
impl<'a, T: Copy> Iterator for ZArray3DIterator<'a, T> {
type Item = ZArray3DIteratorItem<T>;
fn next(&mut self) -> Option<Self::Item> {
match &self.state {
IterState::Done=> None,
IterState::Start=> {
self.state = IterState::Processing;
Some(ZArray3DIteratorItem{x: 0, y: 0, z: 0, value: self.array.patches[0].contents[0]})
},
IterState::Processing => {
let mut x ; let mut y ; let mut z ;
loop {
self.index += 1;
if self.index >= 512 {
self.index = 0;
self.patch += 1;
}
let zyx_lower_pits = REVERSE_ZLUT[self.index];
x = ((self.patch % self.array.pxsize) << 3) | (zyx_lower_pits & 0x07) as usize;
y = (((self.patch / self.array.pxsize) % self.array.pysize ) << 3) | ((zyx_lower_pits >> 3) & 0x07) as usize;
z = ( (self.patch / (self.array.pysize * self.array.pxsize)) << 3) | ((zyx_lower_pits >> 6) & 0x07) as usize;
if x < self.array.xsize && y < self.array.ysize && z < self.array.zsize {
break;
}
if self.patch >= self.array.patches.len() {
self.state = IterState::Done;
return None;
}
}
Some(ZArray3DIteratorItem{x, y, z, value: self.array.patches[self.patch].contents[self.index]})
}
}
}
}
#[test]
fn print_3d_zorder() {
let mut array = ZArray3D::new(8, 8, 8, 0usize);
for z in 0..8usize {
for y in 0..8usize {
for x in 0..8usize {
array.set_unchecked(x, y, z, (z << 6) | (y << 3) | x);
}
}
}
println!("[");
for i in 0..array.patches[0].contents.len() {
print!("{:?}, ", array.patches[0].contents[i]);
if i % 16 == 15{println!()}
}
println!("]");
}
}
#[cfg(test)]
mod tests {
use crate::z2d::ZArray2D;
use crate::z3d::ZArray3D;
use rand::{rngs::StdRng, Rng, SeedableRng};
fn seed_arrays_u8(w: usize, h: usize) -> (Vec<Vec<u8>>, ZArray2D<u8>){
let ref_map: Vec<Vec<u8>> = vec![vec![0u8;w];h];
let map = ZArray2D::new(w, h, 0u8);
return (ref_map, map);
}
#[test]
fn test_zarray2dmap_get_set(){
let h: usize = 601;
let w: usize = 809;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// assert get sizes
assert_eq!(map.dimensions().0, w);
assert_eq!(map.dimensions().1, h);
assert_eq!(map.xsize(), w);
assert_eq!(map.width(), w);
assert_eq!(map.ysize(), h);
assert_eq!(map.height(), h);
// set values
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[y][x] = v;
map.set(x, y, v).unwrap();
}
}
// get values
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[y][x], *map.get(x, y).unwrap());
}
}
}
#[test]
fn test_zarray2dmap_wrapped_get_set(){
let h: usize = 20;
let w: usize = 20;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in -10..10 as isize{
for x in -10..10 as isize {
let v: u8 = prng.gen();
ref_map[((20+y%20)%20) as usize][((20+x%20)%20) as usize] = v;
map.wrapped_set(x, y, v);
}
}
let m: isize = 101;
let v: u8 = prng.gen();
ref_map[((20+m%20)%20) as usize][((20+(3*m)%20)%20) as usize] = v;
map.wrapped_set(3*m, m, v);
// get values
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[y][x], *map.get(x, y).unwrap());
}
}
}
#[test]
fn test_zarray2dmap_bounded_get_set(){
let h: usize = 20;
let w: usize = 20;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in -10..10 as isize{
for x in -10..10 as isize {
let v: u8 = prng.gen();
if x >= 0 && x < w as isize && y >= 0 && y < h as isize {
ref_map[y as usize][x as usize] = v;
}
map.bounded_set(x, y, v);
}
}
let oob: u8 = 127;
let m: isize = 101;
let v: u8 = prng.gen();
map.bounded_set(3*m, m, v); // should be a no-op
// get values
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[y][x], *map.bounded_get(x as isize, y as isize).unwrap_or(&oob));
}
}
assert_eq!(oob, *map.bounded_get(-1, 0).unwrap_or(&oob));
assert_eq!(oob, *map.bounded_get(0, -1).unwrap_or(&oob));
assert_eq!(oob, *map.bounded_get(w as isize, h as isize).unwrap_or(&oob));
}
#[test]
fn test_zarray2dmap_power_of_8(){
let h: usize = 64;
let w: usize = 64;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[y][x] = v;
map.set(x, y, v).unwrap();
}
}
// get values
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[y][x], *map.get(x, y).unwrap());
}
}
}
#[test]
fn test_zarray2dmap_small(){
let h: usize = 3;
let w: usize = 5;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[y][x] = v;
map.set(x, y, v).unwrap();
}
}
// get values
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[y][x], *map.get(x, y).unwrap());
}
}
}
#[test]
fn test_zarray2dmap_performance_neighborsum(){
use std::time::Instant;
let h: usize = 300;
let w: usize = 300;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[y][x] = v;
map.set(x, y, v).unwrap();
}
}
// sum neighbors values with benchmark reference (vecs)
let mut ref_map_sums: Vec<Vec<u16>> = vec![vec![0u16;w];h];
let radius: usize = 2;
let rad_plus = radius * 2 + 1;
let t0 = Instant::now();
for y in radius..h-radius {
for x in radius..w-radius {
let mut sum = 0;
for ry in 0..rad_plus as i32 {
let dy = ry - radius as i32;
for rx in 0..rad_plus as i32 {
let dx = rx - radius as i32;
sum += ref_map[(y as i32+dy) as usize][(x as i32+dx) as usize] as u16;
}
}
ref_map_sums[y][x] = sum;
}
}
let t1 = Instant::now();
let ref_time = (t1-t0).as_secs_f64()*1e6;
println!("Vec<Vec<u16>> {}x{} sum of neighbors in radius {} performance: {} micros", w, h,
radius, ref_time as i32);
// sum neighbors values with ZArray
let mut map_sums = ZArray2D::new(w, h, 0u16);
let t0 = Instant::now();
for y in radius..h-radius {
for x in radius..w-radius {
let mut sum = 0;
for ry in 0..rad_plus as i32 {
let dy = ry - radius as i32;
for rx in 0..rad_plus as i32 {
let dx = rx - radius as i32;
sum += *map.get((x as i32+dx) as usize, (y as i32+dy) as usize).unwrap() as u16;
}
}
map_sums.set(x, y, sum).unwrap();
}
}
let t1 = Instant::now();
let my_time = (t1-t0).as_secs_f64()*1e6;
println!("ZArray2D {}x{} sum of neighbors in radius {} performance: {} micros", w, h,
radius, my_time as i32);
println!("Performance improved by {}%", (100. * (ref_time / my_time - 1.)) as i32);
}
#[test]
fn test_zarray2dmap_performance_pathfinding(){
use std::time::Instant;
use pathfinding::prelude::{absdiff, astar};
let h: usize = 300;
let w: usize = 300;
let (mut ref_map, mut map) = seed_arrays_u8(w, h);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[y][x] = v;
map.set(x, y, v).unwrap();
}
}
// A* pathfinding with benchmark reference (vecs)
let oob: u8 = 127;
let goal: (i32, i32) = (w as i32 - 1, h as i32 - 1);
let start: (i32, i32) = (1, 1);
let t0 = Instant::now();
let result = astar(
&start,
|&(x, y)| vec![
(x+1,y), (x-1,y), (x,y+1), (x,y-1)
].into_iter().map(|p:(i32, i32)| (p,
if p.0 >= 0 && p.1 >= 0 && p.0 < w as i32 && p.1 < h as i32 {
ref_map[p.1 as usize][p.0 as usize] as i32} else {oob as i32})),
|&(x, y)| absdiff(x, goal.0) + absdiff(y, goal.1),
|&p| p == goal
);
let (ref_path, ref_cost) = result.unwrap();
let t1 = Instant::now();
let ref_time = (t1-t0).as_secs_f64()*1e6;
println!("Vec<Vec<u16>> {}x{} A* path from ({},{}) to ({},{}) (path length = {}, cost = \
{}) performance: {} micros",
w, h, start.0, start.1, goal.0, goal.1, ref_path.len(), ref_cost, ref_time);
// A* pathfinding with ZArray
let t0 = Instant::now();
let result = astar(
&start,
|&(x, y)| vec![
(x+1,y), (x-1,y), (x,y+1), (x,y-1)
].into_iter().map(|p:(i32, i32)| (p, *map.bounded_get(p.0 as isize, p.1 as isize )
.unwrap_or(&oob) as i32)),
|&(x, y)| absdiff(x, goal.0) + absdiff(y, goal.1),
|&p| p == goal
);
let (my_path, my_cost) = result.unwrap();
let t1 = Instant::now();
let my_time = (t1-t0).as_secs_f64()*1e6;
println!("ZArray2D {}x{} A* path from ({},{}) to ({},{}) (path length = {}, cost = \
{}) performance: {} micros",
w, h, start.0, start.1, goal.0, goal.1, my_path.len(), my_cost, my_time);
assert_eq!(ref_path.len(), my_path.len());
assert_eq!(ref_cost, my_cost);
println!("Performance improved by {}%", (100. * (ref_time / my_time - 1.)) as i32);
}
fn seed_3darrays_u8(w: usize, h: usize, d: usize) -> (Vec<Vec<Vec<u8>>>, ZArray3D<u8>){
let ref_map: Vec<Vec<Vec<u8>>> = vec![vec![vec![0u8;w];h];d];
let map = ZArray3D::new(w, h, d, 0u8);
return (ref_map, map);
}
#[test]
fn test_zarray3dmap_get_set(){
let h: usize = 11;
let w: usize = 39;
let d: usize = 23;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// assert get sizes
assert_eq!(map.dimensions().0, w);
assert_eq!(map.dimensions().1, h);
assert_eq!(map.dimensions().2, d);
assert_eq!(map.xsize(), w);
assert_eq!(map.width(), w);
assert_eq!(map.ysize(), h);
assert_eq!(map.height(), h);
assert_eq!(map.zsize(), d);
assert_eq!(map.depth(), d);
// set values
for z in 0..d {
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[z][y][x] = v;
map.set(x, y, z, v).unwrap();
}
}
}
// get values
for z in 0..d {
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[z][y][x], *map.get(x, y, z).unwrap());
}
}
}
}
#[test]
fn test_zarray3dmap_wrapped_get_set(){
let h: usize = 20;
let w: usize = 20;
let d: usize = 20;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for z in -10..10 as isize {
for y in -10..10 as isize {
for x in -10..10 as isize {
let v: u8 = prng.gen();
ref_map[((20 + z % 20) % 20) as usize][((20 + y % 20) % 20) as usize][((20 + x % 20) % 20) as usize]
= v;
map.wrapped_set(x, y, z, v);
}
}
}
let m: isize = 101;
let v: u8 = prng.gen();
ref_map[((20+(m/2)%20)%20) as usize][((20+m%20)%20) as usize]
[((20+(3*m)%20)%20) as usize] = v;
map.wrapped_set(3*m, m, m/2, v);
// get values
for z in 0..d {
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[z][y][x], *map.get(x, y, z).unwrap());
}
}
}
}
#[test]
fn test_zarray3dmap_bounded_get_set(){
let h: usize = 20;
let w: usize = 20;
let d: usize = 20;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for z in -10..10 as isize {
for y in -10..10 as isize {
for x in -10..10 as isize {
let v: u8 = prng.gen();
if x >= 0 && x < w as isize && y >= 0 && y < h as isize
&& z >= 0 && z < d as isize{
ref_map[z as usize][y as usize][x as usize] = v;
}
map.bounded_set(x, y, z, v);
}
}
}
let oob: u8 = 127;
let m: isize = 101;
let v: u8 = prng.gen();
map.bounded_set(3*m, m, m/2, v); // should be a no-op
// get values
for z in 0..d {
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[z][y][x],
*map.bounded_get(x as isize, y as isize, z as isize)
.unwrap_or(&oob));
}
}
}
assert_eq!(oob, *map.bounded_get(-1, 0, 0).unwrap_or(&oob));
assert_eq!(oob, *map.bounded_get(0, -1, 0).unwrap_or(&oob));
assert_eq!(oob, *map.bounded_get(0, 0, -1).unwrap_or(&oob));
assert_eq!(oob, *map.bounded_get(w as isize, h as isize, d as isize).unwrap_or(&oob));
}
#[test]
fn test_zarray3dmap_power_of_8(){
let h: usize = 8;
let w: usize = 8;
let d: usize = 8;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for z in 0..d {
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[z][y][x] = v;
map.set(x, y, z, v).unwrap();
}
}
}
// get values
for z in 0..d {
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[z][y][x], *map.get(x, y, z).unwrap());
}
}
}
}
#[test]
fn test_zarray3dmap_small(){
let h: usize = 3;
let w: usize = 2;
let d: usize = 2;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for z in 0..d {
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[z][y][x] = v;
map.set(x, y, z, v).unwrap();
}
}
}
// get values
for z in 0..d {
for y in 0..h {
for x in 0..w {
assert_eq!(ref_map[z][y][x], *map.get(x, y, z).unwrap());
}
}
}
}
#[test]
fn test_zarray3dmap_performance_neighborsum(){
use std::time::Instant;
let h: usize = 20;
let w: usize = 10;
let d: usize = 30;
let (mut ref_map, mut map) = seed_3darrays_u8(w, h, d);
let mut prng = StdRng::seed_from_u64(20220331u64);
// set values
for z in 0..d {
for y in 0..h {
for x in 0..w {
let v: u8 = prng.gen();
ref_map[z][y][x] = v;
map.set(x, y, z, v).unwrap();
}
}
}
// sum neighbors values with benchmark reference (vecs)
let mut ref_map_sums: Vec<Vec<Vec<u32>>> = vec![vec![vec![0u32;w];h];d];
let radius: usize = 2;
let rad_plus = radius * 2 + 1;
let t0 = Instant::now();
for z in radius..d - radius {
for y in radius..h - radius {
for x in radius..w - radius {
let mut sum = 0;
for rz in 0..rad_plus as i32 {
let dz = rz - radius as i32;
for ry in 0..rad_plus as i32 {
let dy = ry - radius as i32;
for rx in 0..rad_plus as i32 {
let dx = rx - radius as i32;
sum += ref_map[(z as i32 + dz) as usize][(y as i32 + dy) as usize]
[(x as i32 + dx) as usize] as u32;
}
}
}
ref_map_sums[z][y][x] = sum;
}
}
}
let t1 = Instant::now();
let ref_time = (t1-t0).as_secs_f64()*1e6;
println!("Vec<Vec<u16>> {}x{}x{} sum of neighbors in radius {} performance: {} micros",
w, h, d, radius, ref_time as i32);
// sum neighbors values with ZArray
let mut map_sums = ZArray3D::new(w, h, d, 0u32);
let t0 = Instant::now();
for z in radius..d - radius {
for y in radius..h - radius {
for x in radius..w - radius {
let mut sum = 0;
for rz in 0..rad_plus as i32 {
let dz = rz - radius as i32;
for ry in 0..rad_plus as i32 {
let dy = ry - radius as i32;
for rx in 0..rad_plus as i32 {
let dx = rx - radius as i32;
sum += *map.get((x as i32+dx) as usize, (y as i32+dy) as usize,
(z as i32+dz) as usize).unwrap() as u32;
}
}
}
map_sums.set(x, y, z, sum).unwrap();
}
}
}
let t1 = Instant::now();
let my_time = (t1-t0).as_secs_f64()*1e6;
println!("ZArray2D {}x{}x{} sum of neighbors in radius {} performance: {} micros", w, h, d,
radius, my_time as i32);
println!("Performance improved by {}%", (100. * (ref_time / my_time - 1.)) as i32);
}
#[test]
fn test_erosion_sim(){
let width = 100;
let length = 200;
let depth = 25;
let air = 0f32;
let soil_hardness = 1f32;
let rock_hardness = 8f32;
let drip_power = 1.5f32;
let iterations = 12;
let mut map = ZArray3D::new(width, length, depth, air);
map.fill(0,0,5, width,length,depth, soil_hardness).unwrap();
map.fill(0,0,15, width,length,depth, rock_hardness).unwrap();
for boulder in [(34,88,6), (66,122,9), (11,154,5), (35,93,8), (72,75,12)]{
map.set(boulder.0, boulder.1, boulder.2, rock_hardness).unwrap();
}
for _ in 0..iterations{
for x in 0..width{for y in 0..length{
let mut drip = drip_power;
let mut z = 0;
while drip > 0f32 {
let h = *map.bounded_get(x as isize, y as isize, z).unwrap_or(&100f32);
if h > drip {
map.bounded_set(x as isize, y as isize, z, h - drip);
drip = 0.;
} else {
map.bounded_set(x as isize, y as isize, z, 0.);
drip -= h;
}
z += 1;
}
}}
}
}
#[test]
fn iter_2d_test() {
test_2d_iter(8,8);
test_2d_iter(3,5);
test_2d_iter(11,5);
test_2d_iter(3,11);
test_2d_iter(57,101);
test_2d_iter(111,51);
}
fn test_2d_iter(w: usize, h: usize) {
let a1 = init_with_count_2d(w, h);
let a2 = init_with_count_2d(w, h);
for item in a1.iter() {
assert_eq!(item.value, *a2.get(item.x, item.y).expect("Out of bounds"));
}
}
fn init_with_count_2d(w: usize, h: usize) -> ZArray2D<i32> {
let mut array = ZArray2D::new(w, h, 0i32);
let mut i: i32 = 0;
for y in 0..h {
for x in 0..w {
array.set_unchecked(x, y, i);
i += 1;
}
}
array
}
#[test]
fn iter_3d_test() {
test_3d_iter(8,8,8);
test_3d_iter(3,5,4);
test_3d_iter(11,5,3);
test_3d_iter(3,11,1);
test_3d_iter(57,101,89);
test_3d_iter(111,51,101);
}
fn test_3d_iter(w: usize, h: usize, l: usize) {
let a1 = init_with_count_3d(w, h, l);
let a2 = init_with_count_3d(w, h, l);
for item in a1.iter() {
assert_eq!(item.value, *a2.get(item.x, item.y, item.z).expect("Out of bounds"));
}
}
fn init_with_count_3d(w: usize, h: usize, l: usize) -> ZArray3D<i32> {
let mut array = ZArray3D::new(w, h, l, 0i32);
let mut i: i32 = 0;
for z in 0..l {
for y in 0..h {
for x in 0..w {
array.set_unchecked(x, y, z, i);
i += 1;
}
}
}
array
}
}