diff --git a/Cargo.lock b/Cargo.lock index 005124c500..c5ec1fd29d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4680,6 +4680,15 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a65843dfefbafd3c879c683306959a6de478443ffe9c9adf02f5976432402d7" +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -5193,6 +5202,20 @@ dependencies = [ "semver", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustgis" version = "0.8.0" @@ -5224,6 +5247,7 @@ dependencies = [ "i_overlay 9.2.1", "log", "proptest", + "rustfft", "rustgis-data", "rustgis-geom", "s2", @@ -6236,6 +6260,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "strict-num" version = "0.1.1" @@ -6785,6 +6815,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "tree_magic_mini" version = "3.2.2" diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 445fbd13ea..bf75c63ed2 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -36,24 +36,25 @@ objc2-core-foundation, objc2-core-graphics, objc2-io-kit, objc2-metal, objc2-qua objc2-system-configuration, objc2-uniform-type-identifiers, once_cell, openssl-probe, ordered-stream, owned_ttf_parser, parking, parking_lot, parking_lot_core, peniko, percent-encoding, petgraph, pin-project, pin-project-internal, pin-project-lite, piper, pkg-config, png, polling, -pollster, polycool, postgres, postgres-protocol, postgres-types, presser, proc-macro2, profiling, -pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, pyo3-macros-backend, quote, rand, range-alloc, -raw-window-handle, raw-window-metal, rayon, rayon-core, regex, regex-automata, regex-syntax, -renderdoc-sys, resvg, ring, robust, roxmltree, rstar, rustc-hash, rustc_version, rustix, rustls, -rustls-native-certs, rustls-pemfile, rustls-platform-verifier, rustversion, ryu, s2, scoped-tls, -scopeguard, secrecy, secret-service, security-framework, security-framework-sys, self_cell, semver, -send_wrapper, seq-macro, serde, serde_core, serde_derive, serde_ignored, serde_json, serde_repr, -sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, simplecss, siphasher, smallvec, -smol_str, socket2, spade, spirv, spki, stable_deref_trait, static_assertions, subsetter, svgtypes, -syn, sys-locale, tar, tempfile, thiserror, thiserror-impl, tiberius-macros, time, time-core, -tinyvec, tokio-postgres, ttf-parser, type-map, typed-path, unicode-bidi, unicode-ident, -unicode-normalization, unicode-properties, unicode-segmentation, unicode-width, ureq, ureq-proto, -url, usvg, utf8-zero, utf8_iter, uuid, vcpkg, vello_common, vello_cpu, version_check, wasm-bindgen, -wasm-bindgen-futures, wasm-bindgen-macro, wasm-bindgen-macro-support, wasm-bindgen-shared, -wasm-encoder, wasmi, wasmi_collections, wasmi_core, wasmi_ir, wasmparser, wast, wat, web-sys, weezl, -wgpu, wgpu-core, wgpu-core-deps-apple, wgpu-core-deps-wasm, wgpu-core-deps-windows-linux-android, -wgpu-hal, wgpu-naga-bridge, wgpu-types, whoami, winauth, wkt, wl-clipboard-rs, x11rb, -x11rb-protocol, x509-cert, xattr, zeroize, zeroize_derive, zune-core, zune-jpeg +pollster, polycool, postgres, postgres-protocol, postgres-types, presser, primal-check, proc-macro2, +profiling, pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, pyo3-macros-backend, quote, rand, +range-alloc, raw-window-handle, raw-window-metal, rayon, rayon-core, regex, regex-automata, +regex-syntax, renderdoc-sys, resvg, ring, robust, roxmltree, rstar, rustc-hash, rustc_version, +rustix, rustls, rustls-native-certs, rustls-pemfile, rustls-platform-verifier, rustversion, ryu, s2, +scoped-tls, scopeguard, secrecy, secret-service, security-framework, security-framework-sys, +self_cell, semver, send_wrapper, seq-macro, serde, serde_core, serde_derive, serde_ignored, +serde_json, serde_repr, sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, simplecss, +siphasher, smallvec, smol_str, socket2, spade, spirv, spki, stable_deref_trait, static_assertions, +subsetter, svgtypes, syn, sys-locale, tar, tempfile, thiserror, thiserror-impl, tiberius-macros, +time, time-core, tinyvec, tokio-postgres, ttf-parser, type-map, typed-path, unicode-bidi, +unicode-ident, unicode-normalization, unicode-properties, unicode-segmentation, unicode-width, ureq, +ureq-proto, url, usvg, utf8-zero, utf8_iter, uuid, vcpkg, vello_common, vello_cpu, version_check, +wasm-bindgen, wasm-bindgen-futures, wasm-bindgen-macro, wasm-bindgen-macro-support, +wasm-bindgen-shared, wasm-encoder, wasmi, wasmi_collections, wasmi_core, wasmi_ir, wasmparser, wast, +wat, web-sys, weezl, wgpu, wgpu-core, wgpu-core-deps-apple, wgpu-core-deps-wasm, +wgpu-core-deps-windows-linux-android, wgpu-hal, wgpu-naga-bridge, wgpu-types, whoami, winauth, wkt, +wl-clipboard-rs, x11rb, x11rb-protocol, x509-cert, xattr, zeroize, zeroize_derive, zune-core, +zune-jpeg ==================================================================================================== Apache License @@ -1398,7 +1399,8 @@ limitations under the License. ==================================================================================================== Apache License 2.0 Used by: crc32fast, dpi, fallible-iterator, fallible-streaming-iterator, foreign-types, foreign-types-macros, -foreign-types-shared, hex, quick-error, stringprep, unicode-general-category, winapi, winit +foreign-types-shared, hex, quick-error, rustfft, strength_reduce, stringprep, +unicode-general-category, winapi, winit ==================================================================================================== Apache License @@ -6666,6 +6668,213 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +==================================================================================================== +Apache License 2.0 +Used by: transpose +==================================================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2022 The transpose developers + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + ==================================================================================================== Apache License 2.0 Used by: typenum diff --git a/apps/rustgis-mobile/THIRD-PARTY-LICENSES.txt b/apps/rustgis-mobile/THIRD-PARTY-LICENSES.txt index b13941ec3e..7def720fb0 100644 --- a/apps/rustgis-mobile/THIRD-PARTY-LICENSES.txt +++ b/apps/rustgis-mobile/THIRD-PARTY-LICENSES.txt @@ -24,26 +24,26 @@ itertools, itoa, jni, jni-macros, jni-sys-macros, jobserver, khronos-egl, kurbo, lerc-core, lerc-reader, libc, linebender_resource_handle, linux-raw-sys, litrs, lock_api, log, lyon, lyon_algorithms, lyon_geom, lyon_path, lyon_tessellation, md-5, miniz_oxide, multiversion_no_op, mysql, mysql_common, naga, naga-types, ndk, ndk-context, ndk-sys, nohash-hasher, num-bigint, -num-conv, num-integer, num-traits, num_enum, num_enum_derive, objc2-cloud-kit, objc2-contacts, -objc2-core-data, objc2-core-foundation, objc2-core-graphics, objc2-core-image, objc2-core-location, -objc2-core-text, objc2-io-kit, objc2-metal, objc2-quartz-core, objc2-system-configuration, -objc2-ui-kit, objc2-uniform-type-identifiers, objc2-user-notifications, once_cell, openssl-probe, -owned_ttf_parser, parking_lot, parking_lot_core, peniko, percent-encoding, pin-project-lite, -pkg-config, png, pollster, polycool, postgres, postgres-protocol, postgres-types, presser, -proc-macro2, profiling, quote, rand, raw-window-handle, raw-window-metal, rayon, rayon-core, regex, -regex-automata, regex-syntax, renderdoc-sys, resvg, ring, robust, roxmltree, rstar, rustc-hash, -rustc_version, rustix, rustls, rustls-native-certs, rustls-pemfile, rustls-platform-verifier, -rustls-platform-verifier-android, rustversion, ryu, s2, scopeguard, secrecy, security-framework, -security-framework-sys, self_cell, semver, seq-macro, serde, serde_core, serde_derive, -serde_ignored, serde_json, sha1, sha2, shlex, sif-itree, simd_cesu8, simdutf8, simplecss, siphasher, -smallvec, smol_str, socket2, spade, spirv, spki, stable_deref_trait, static_assertions, subsetter, -svgtypes, syn, sys-locale, tempfile, thiserror, thiserror-impl, tiberius-macros, time, time-core, -tinyvec, tokio-postgres, ttf-parser, type-map, typed-path, unicode-bidi, unicode-ident, -unicode-normalization, unicode-properties, unicode-segmentation, unicode-width, ureq, ureq-proto, -url, usvg, utf8-zero, utf8_iter, uuid, vcpkg, vello_common, vello_cpu, version_check, wasmi, -wasmi_collections, wasmi_core, wasmi_ir, wasmparser, weezl, wgpu, wgpu-core, wgpu-core-deps-apple, -wgpu-core-deps-windows-linux-android, wgpu-hal, wgpu-naga-bridge, wgpu-types, whoami, wkt, -x509-cert, zeroize, zeroize_derive, zune-core, zune-jpeg +num-complex, num-conv, num-integer, num-traits, num_enum, num_enum_derive, objc2-cloud-kit, +objc2-contacts, objc2-core-data, objc2-core-foundation, objc2-core-graphics, objc2-core-image, +objc2-core-location, objc2-core-text, objc2-io-kit, objc2-metal, objc2-quartz-core, +objc2-system-configuration, objc2-ui-kit, objc2-uniform-type-identifiers, objc2-user-notifications, +once_cell, openssl-probe, owned_ttf_parser, parking_lot, parking_lot_core, peniko, percent-encoding, +pin-project-lite, pkg-config, png, pollster, polycool, postgres, postgres-protocol, postgres-types, +presser, primal-check, proc-macro2, profiling, quote, rand, raw-window-handle, raw-window-metal, +rayon, rayon-core, regex, regex-automata, regex-syntax, renderdoc-sys, resvg, ring, robust, +roxmltree, rstar, rustc-hash, rustc_version, rustix, rustls, rustls-native-certs, rustls-pemfile, +rustls-platform-verifier, rustls-platform-verifier-android, rustversion, ryu, s2, scopeguard, +secrecy, security-framework, security-framework-sys, self_cell, semver, seq-macro, serde, +serde_core, serde_derive, serde_ignored, serde_json, sha1, sha2, shlex, sif-itree, simd_cesu8, +simdutf8, simplecss, siphasher, smallvec, smol_str, socket2, spade, spirv, spki, stable_deref_trait, +static_assertions, subsetter, svgtypes, syn, sys-locale, tempfile, thiserror, thiserror-impl, +tiberius-macros, time, time-core, tinyvec, tokio-postgres, ttf-parser, type-map, typed-path, +unicode-bidi, unicode-ident, unicode-normalization, unicode-properties, unicode-segmentation, +unicode-width, ureq, ureq-proto, url, usvg, utf8-zero, utf8_iter, uuid, vcpkg, vello_common, +vello_cpu, version_check, wasmi, wasmi_collections, wasmi_core, wasmi_ir, wasmparser, weezl, wgpu, +wgpu-core, wgpu-core-deps-apple, wgpu-core-deps-windows-linux-android, wgpu-hal, wgpu-naga-bridge, +wgpu-types, whoami, wkt, x509-cert, zeroize, zeroize_derive, zune-core, zune-jpeg ==================================================================================================== Apache License @@ -1594,7 +1594,7 @@ Used by: connection-string ==================================================================================================== Apache License 2.0 Used by: crc32fast, dpi, env_filter, fallible-iterator, fallible-streaming-iterator, jni-sys, quick-error, -stringprep, unicode-general-category, winit +rustfft, strength_reduce, stringprep, unicode-general-category, winit ==================================================================================================== Apache License @@ -6241,6 +6241,213 @@ Used by: toml_datetime, toml_edit, toml_parser See the License for the specific language governing permissions and limitations under the License. +==================================================================================================== +Apache License 2.0 +Used by: transpose +==================================================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2022 The transpose developers + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + ==================================================================================================== Apache License 2.0 Used by: typenum diff --git a/apps/rustgis-python/THIRD-PARTY-LICENSES.txt b/apps/rustgis-python/THIRD-PARTY-LICENSES.txt index c96d0f38da..5d3cae31c4 100644 --- a/apps/rustgis-python/THIRD-PARTY-LICENSES.txt +++ b/apps/rustgis-python/THIRD-PARTY-LICENSES.txt @@ -29,10 +29,10 @@ num-complex, num-conv, num-integer, num-iter, num-rational, num-traits, objc2-co objc2-io-kit, objc2-system-configuration, once_cell, openssl-probe, ordered-stream, owned_ttf_parser, parking, parking_lot, parking_lot_core, peniko, percent-encoding, pin-project-lite, piper, pkg-config, png, polling, polycool, postgres, postgres-protocol, -postgres-types, proc-macro2, pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, pyo3-macros-backend, -quote, rand, rayon, rayon-core, regex, regex-automata, regex-syntax, resvg, ring, robust, roxmltree, -rstar, rustc-hash, rustc_version, rustix, rustls, rustls-native-certs, rustls-pemfile, -rustls-platform-verifier, rustversion, ryu, s2, scopeguard, secrecy, secret-service, +postgres-types, primal-check, proc-macro2, pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, +pyo3-macros-backend, quote, rand, rayon, rayon-core, regex, regex-automata, regex-syntax, resvg, +ring, robust, roxmltree, rstar, rustc-hash, rustc_version, rustix, rustls, rustls-native-certs, +rustls-pemfile, rustls-platform-verifier, rustversion, ryu, s2, scopeguard, secrecy, secret-service, security-framework, security-framework-sys, semver, seq-macro, serde, serde_core, serde_derive, serde_ignored, serde_json, serde_repr, sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, simplecss, siphasher, smallvec, socket2, spade, spki, stable_deref_trait, subsetter, svgtypes, syn, @@ -1313,7 +1313,8 @@ limitations under the License. ==================================================================================================== Apache License 2.0 -Used by: crc32fast, fallible-iterator, fallible-streaming-iterator, hex, quick-error, stringprep, winapi +Used by: crc32fast, fallible-iterator, fallible-streaming-iterator, hex, quick-error, rustfft, +strength_reduce, stringprep, winapi ==================================================================================================== Apache License @@ -5753,6 +5754,213 @@ Used by: toml_datetime, toml_edit, toml_parser See the License for the specific language governing permissions and limitations under the License. +==================================================================================================== +Apache License 2.0 +Used by: transpose +==================================================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2022 The transpose developers + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + ==================================================================================================== Apache License 2.0 Used by: typenum diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml index d4d33413e7..0402b3e33f 100644 --- a/crates/analysis/Cargo.toml +++ b/crates/analysis/Cargo.toml @@ -15,6 +15,8 @@ geo = { workspace = true } # Not 9.2.0: of 8,674 random groups it wrote invalid polygons for 5 (one of valid input), and 9.2.1 # for none. i_overlay9 = { package = "i_overlay", version = "9.2.1" } +# FFTs for texture shading (#3146): pure Rust, MIT or Apache-2.0, builds for wasm32. +rustfft = "6.4" a5 = { workspace = true } h3o = { workspace = true } s2 = { workspace = true } diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 23b6ff5864..acb4a1be75 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -33,6 +33,7 @@ mod repair; pub mod selection; pub mod sketch_edit; mod stats; +pub mod texture; pub mod tissot; mod tools; pub mod topology; diff --git a/crates/analysis/src/texture.rs b/crates/analysis/src/texture.rs new file mode 100644 index 0000000000..75e576e177 --- /dev/null +++ b/crates/analysis/src/texture.rs @@ -0,0 +1,309 @@ +//! Texture shading (#3146): Leland Brown's fractional Laplacian of an elevation model, which draws +//! valleys dark and ridges light at every scale at once, with no light direction. +//! +//! In frequency the filter multiplies the elevations by `|k|^α` (`k` in radians per metre), the +//! symbol of `(−Δ)^(α/2)`: α 2 would be the Laplacian itself, and below 1 it keeps the large +//! valleys as well as the small ones. A whole-model filter in frequency is a kernel as large as +//! the model in space, so it is worked out with FFTs. +//! +//! The method is Leland Brown's, "Texture Shading: A New Technique for Depicting Terrain Relief", +//! a paper at the 9th ICA Mountain Cartography Workshop, Banff, Canada, 22–26 April 2014. This +//! code was written from that publication; no other code was followed. +//! +//! The model's mean is removed and its edges are mirrored [`PAD`] cells out on each side, so that +//! the FFT, which wraps the grid around, doesn't set one edge against the other. Each padded side +//! is then grown to a size of small factors (2, 3 and 5), on which the FFT is fastest. + +use rustfft::FftPlanner; +use rustfft::num_complex::Complex; +use rustgis_data::raster::Raster; + +use crate::rasterops::{NODATA, max_pixels, new_band}; + +/// The cells mirrored out on each side of the model before the FFT. +pub const PAD: usize = 64; +/// About how many cells one item of a pass holds: enough to share out on threads, few enough +/// items that a small model is shaded in a few looks at Cancel. +const BLOCK_CELLS: usize = 1 << 16; + +/// The fractional Laplacian of band `b` of `r` with exponent `alpha`: positive on ridges, negative +/// in valleys, in the band's unit per metre^α, [`NODATA`] where the band has none. Cells are +/// measured in metres ([`Raster::cell_size_m`]: a geographic model at its middle's latitude, a +/// projected one's unit converted). An alpha the cells overflow Float32 with is an error. +/// +/// A cell with no value is taken at the model's mean, so a hole stays level: the texture next to +/// it is of the ground around it and a flat hole. +pub fn texture(r: &Raster, b: usize, alpha: f64) -> Result, String> { + texture_on(None, r, b, alpha) +} + +/// [`texture`] on `threads` threads (none: as many as pay off): the same cells on any. +/// +/// Three passes, each by blocks of rows on the threads: the padded model is read and its rows transformed; +/// each column is transformed, filtered and transformed back; then each row of the model is +/// transformed back. Beyond the model and the output, it holds two padded grids of complex +/// 32-bit numbers (16 bytes a padded cell), the first only until the columns are taken from it. +pub(crate) fn texture_on(threads: Option, r: &Raster, b: usize, alpha: f64) -> Result, String> { + if !(alpha.is_finite() && alpha > 0.0) { + return Err("alpha must be a number more than 0".into()); + } + let data = r.bands.get(b).map(|b| b.data.as_slice()).ok_or_else(|| format!("{} has no band {}", r.name, b + 1))?; + let (w, h) = (r.width as usize, r.height as usize); + if data.len() != w.saturating_mul(h) { + return Err(format!("band {} of {} doesn't hold its {w} × {h} cells", b + 1, r.name)); + } + let valid = |v: f32| r.is_valid(v) && v.is_finite(); + let (sum, count) = data.iter().filter(|v| valid(**v)).fold((0.0f64, 0usize), |(s, n), v| (s + f64::from(*v), n + 1)); + if count == 0 { + return Err(format!("band {} of {} has no values", b + 1, r.name)); + } + let mean = sum / count as f64; + // A projected system's unit may be a foot: `cell_size_m` gives its cells in that unit. + let unit = if r.crs.is_geographic() { 1.0 } else { r.crs.metres_per_unit() }; + let (cx, cy) = r.cell_size_m(); + let (cx, cy) = (cx * unit, cy * unit); + if !(cx.is_finite() && cy.is_finite() && cx > 0.0 && cy > 0.0) { + return Err(format!("{}'s cells have no size", r.name)); + } + let too_large = || { + format!( + "{} is too large for texture shading: with its margins, more than the {} cells this computer can hold", + r.name, + max_pixels() + ) + }; + // A side past the limit on its own is refused before it is padded, so the sum can't overflow. + let side = |n: usize| (n <= max_pixels()).then(|| smooth(n + 2 * PAD)); + let (Some(pw), Some(ph)) = (side(w), side(h)) else { return Err(too_large()) }; + if pw.saturating_mul(ph) > max_pixels() { + return Err(too_large()); + } + let mut planner = FftPlanner::::new(); + let (row_fwd, row_inv) = (planner.plan_fft_forward(pw), planner.plan_fft_inverse(pw)); + let (col_fwd, col_inv) = (planner.plan_fft_forward(ph), planner.plan_fft_inverse(ph)); + let scratch_len = [&row_fwd, &row_inv, &col_fwd, &col_inv].iter().map(|f| f.get_inplace_scratch_len()).max().unwrap_or(0); + let scratch_bytes = (scratch_len + pw.max(ph)) * std::mem::size_of::>(); + // A padded cell takes a few dozen operations in each pass, some units of MIN_ROW_WORK's. + let work = pw.saturating_mul(ph).saturating_mul(4); + let on = |rows: usize| threads.unwrap_or_else(|| crate::parallel::threads_for_rows(rows, work, scratch_bytes)); + let zero = Complex::new(0.0f32, 0.0); + let scratch = || vec![zero; scratch_len]; + + // Each item of a pass is a block of lines of about BLOCK_CELLS cells: `lines(len)` of them. + let lines = |len: usize| (BLOCK_CELLS / len.max(1)).max(1); + + // The padded model, less its mean, a row after another, each transformed along x. + let mut rows = new_band(pw, ph, zero)?; + let k = lines(pw); + crate::control::begin(ph.div_ceil(k)); + crate::parallel::for_each_row(rows.chunks_mut(pw * k), on(ph.div_ceil(k)), scratch, |s, i, block: &mut [Complex]| { + for (j, line) in block.chunks_mut(pw).enumerate() { + let from = mirror((i * k + j) as i64 - PAD as i64, h) * w; + for (x, cell) in line.iter_mut().enumerate() { + let v = data.get(from + mirror(x as i64 - PAD as i64, w)).copied().filter(|v| valid(*v)); + *cell = Complex::new(v.map_or(0.0, |v| (f64::from(v) - mean) as f32), 0.0); + } + row_fwd.process_with_scratch(line, s); + } + })?; + + // Each column, transformed along y, filtered and transformed back. + let mut cols = new_band(ph, pw, zero)?; + let (kx_unit, ky_unit) = (std::f64::consts::TAU / (pw as f64 * cx), std::f64::consts::TAU / (ph as f64 * cy)); + let k = lines(ph); + crate::control::begin(pw.div_ceil(k)); + crate::parallel::for_each_row(cols.chunks_mut(ph * k), on(pw.div_ceil(k)), scratch, |s, i, block: &mut [Complex]| { + for (j, line) in block.chunks_mut(ph).enumerate() { + let x = i * k + j; + for (y, cell) in line.iter_mut().enumerate() { + *cell = rows.get(y * pw + x).copied().unwrap_or(zero); + } + col_fwd.process_with_scratch(line, s); + let kx = signed(x, pw) * kx_unit; + for (y, cell) in line.iter_mut().enumerate() { + *cell *= kx.hypot(signed(y, ph) * ky_unit).powf(alpha) as f32; + } + col_inv.process_with_scratch(line, s); + } + })?; + drop(rows); + + // Each of the model's rows transformed back, and its cells taken out of the margins. + let mut out = new_band(w, h, NODATA)?; + let scale = 1.0 / (pw as f64 * ph as f64); + let k = lines(pw); + crate::control::begin(h.div_ceil(k)); + crate::parallel::for_each_row( + out.chunks_mut(w * k), + on(h.div_ceil(k)), + || (vec![zero; pw], scratch()), + |(row, s), i, block: &mut [f32]| { + for (j, line) in block.chunks_mut(w).enumerate() { + let y = i * k + j; + for (x, cell) in row.iter_mut().enumerate() { + *cell = cols.get(x * ph + y + PAD).copied().unwrap_or(zero); + } + row_inv.process_with_scratch(row, s); + for (x, (cell, padded)) in line.iter_mut().zip(row.iter().skip(PAD)).enumerate() { + if data.get(y * w + x).copied().is_some_and(valid) { + *cell = (f64::from(padded.re) * scale) as f32; + } + } + } + }, + )?; + // |k|^α past Float32 (a large alpha on fine cells) turns every cell to NaN. + if out.iter().any(|v| !v.is_finite()) { + return Err(format!("alpha {alpha} is too large for {}'s cells: the texture overflows", r.name)); + } + Ok(out) +} + +/// The cell of `0..n` that `i` falls on mirrored at the edges, the edge cell repeated +/// (… 1 0 | 0 1 2 … n−1 | n−1 n−2 …), as many times as it takes. +fn mirror(i: i64, n: usize) -> usize { + let n = n.max(1) as i64; + let m = i.rem_euclid(2 * n); + (if m < n { m } else { 2 * n - 1 - m }) as usize +} + +/// The frequency of the FFT's `i`th of `n` outputs, in cycles over the grid: `i` up to half of +/// `n`, then negative. +fn signed(i: usize, n: usize) -> f64 { + if 2 * i <= n { i as f64 } else { i as f64 - n as f64 } +} + +/// The smallest size from `n` on with no prime factor beyond 5. +fn smooth(n: usize) -> usize { + let rough = |mut m: usize| { + for p in [2, 3, 5] { + while m > 0 && m.is_multiple_of(p) { + m /= p; + } + } + m > 1 + }; + let mut n = n.max(1); + while rough(n) { + n += 1; + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; + + /// A `width × height` grid of 30 m × 20 m cells in UTM 23S, each `z(col, row)`, -9999 its no-data. + fn dem(width: u32, height: u32, z: impl Fn(f64, f64) -> f64) -> Raster { + dem_in(Crs::Epsg(32723), (30., 20.), width, height, z) + } + + /// [`dem`] in `crs`, its cells `size` of its units across and down. + fn dem_in(crs: Crs, size: (f64, f64), width: u32, height: u32, z: impl Fn(f64, f64) -> f64) -> Raster { + let values = (0..height).flat_map(|row| (0..width).map(move |col| (col, row))).map(|(c, r)| z(c.into(), r.into()) as f32).collect(); + let transform = GeoTransform { origin_x: 600_000., origin_y: 7_750_000., pixel_width: size.0, pixel_height: -size.1 }; + Raster::new("dem", width, height, vec![values], transform, crs, Some(-9999.), ColorHint::Gray, "Float32").unwrap() + } + + /// Cells in feet are measured in metres, so a model in feet has the texture of the same + /// ground in metres. + #[test] + fn cells_in_feet_are_measured_in_metres() { + let feet = Crs::Epsg(2263); + let metre = feet.metres_per_unit(); + assert!((metre - 0.3048).abs() < 1e-4, "{metre}"); + let hill = |c: f64, rr: f64| 300.0 + 40.0 * (c / 6.0).sin() * (rr / 4.0).cos(); + let got = texture(&dem_in(feet, (100., 100.), 50, 40, hill), 0, 0.5).unwrap(); + let want = texture(&dem_in(Crs::Epsg(32723), (100. * metre, 100. * metre), 50, 40, hill), 0, 0.5).unwrap(); + for (g, w) in got.iter().zip(&want) { + assert!((g - w).abs() <= 1e-5 * w.abs().max(1e-3), "{g} in feet, {w} in metres"); + } + } + + /// An alpha that overflows the filter on fine cells (4.4 rad/m to the 100th is 1e64, past + /// Float32) is refused, not written as cells of NaN. + #[test] + fn an_alpha_that_overflows_is_refused() { + let r = dem_in(Crs::Epsg(32723), (1., 1.), 20, 20, |c, rr| 100.0 + (c / 3.0).sin() + (rr / 2.0).cos()); + assert_eq!(texture(&r, 0, 100.0), Err("alpha 100 is too large for dem's cells: the texture overflows".into())); + assert!(texture(&r, 0, 2.0).unwrap().iter().all(|v| v.is_finite())); + } + + #[test] + fn padded_sizes_have_small_factors() { + assert_eq!([smooth(0), smooth(7), smooth(192), smooth(193), smooth(1000 + 128)], [1, 8, 192, 200, 1152]); + assert_eq!((-3..9).map(|i| mirror(i, 3)).collect::>(), [2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 1, 2]); + assert_eq!([mirror(-5, 1), mirror(4, 1)], [0, 0]); + } + + /// Waves the mirrored margins continue exactly (64 cells, 192 with them, a whole number of + /// waves): each comes out times its wavenumber to the α, positive on its crests, and the cells + /// are measured on their own sides (30 m across, 20 m down). + #[test] + fn a_wave_is_multiplied_by_its_wavenumber_to_the_alpha() { + let (across, down) = (64.0, 32.0); + let wave = |c: f64, r: f64| { + let (u, v) = ((c + 0.5) / across, (r + 0.5) / down); + ((std::f64::consts::TAU * u).cos(), (std::f64::consts::TAU * v).cos()) + }; + let r = dem(64, 64, |c, rr| 500.0 + 100.0 * wave(c, rr).0 + 40.0 * wave(c, rr).1); + for alpha in [0.5, 0.8] { + let (kx, ky) = (std::f64::consts::TAU / (across * 30.0), std::f64::consts::TAU / (down * 20.0)); + let got = texture(&r, 0, alpha).unwrap(); + for (i, v) in got.iter().enumerate() { + let (c, rr) = ((i % 64) as f64, (i / 64) as f64); + let want = 100.0 * kx.powf(alpha) * wave(c, rr).0 + 40.0 * ky.powf(alpha) * wave(c, rr).1; + assert!((f64::from(*v) - want).abs() < 1e-3 + 1e-4 * want.abs(), "α {alpha}, cell {c}, {rr}: {v} for {want}"); + } + } + } + + /// A peak by the west edge reaches the east edge only across the model, as it would without + /// the FFT wrapping the grid around: there, three cells away through the wrap, it would be as + /// strong as three cells east of it. + #[test] + fn the_edges_dont_wrap_around() { + let r = dem(100, 40, |c, rr| 800.0 + 200.0 * (-((c - 2.0).powi(2) + (rr - 20.0).powi(2)) / 2.0).exp()); + let got = texture(&r, 0, 0.5).unwrap(); + let (near, east) = (got[20 * 100 + 5], got[20 * 100 + 99]); + assert!(near < 0.0 && east.abs() < 0.01 * near.abs(), "{near} beside the peak, {east} at the east edge"); + } + + #[test] + fn no_data_stays_no_data_and_doesnt_count() { + let hill = |c: f64, rr: f64| 900.0 + 50.0 * ((c / 5.0).sin() + (rr / 7.0).cos()); + let r = dem(30, 20, |c, rr| if (c, rr) == (10.0, 10.0) { -9999.0 } else { hill(c, rr) }); + let got = texture(&r, 0, 0.5).unwrap(); + assert_eq!(got[10 * 30 + 10], NODATA); + assert!(got.iter().enumerate().all(|(i, v)| i == 310 || v.is_finite()), "{got:?}"); + let empty = dem(4, 4, |_, _| -9999.0); + assert_eq!(texture(&empty, 0, 0.5), Err("band 1 of dem has no values".into())); + assert_eq!(texture(&r, 0, 0.0), Err("alpha must be a number more than 0".into())); + assert_eq!(texture(&r, 1, 0.5), Err("dem has no band 2".into())); + } + + /// Rows go in blocks of about [`BLOCK_CELLS`] cells, so a small model looks at Cancel a few + /// times, not once a row of each pass, and stops at the look it is cancelled at. + #[test] + fn a_small_model_looks_at_cancel_a_few_times() { + use crate::control::Control; + let r = dem(100, 80, |c, rr| 700.0 + 80.0 * (c / 9.0).sin() * (rr / 6.0).cos()); + let counting = Control::cancelled_at_look(u64::MAX); + crate::run_under("Texture", &counting, || texture(&r, 0, 0.5)).unwrap(); + assert!((3..=8).contains(&counting.looked()), "looked {} times", counting.looked()); + let cancel = Control::cancelled_at_look(2); + let err = crate::run_under("Texture", &cancel, || texture(&r, 0, 0.5)).unwrap_err(); + assert!(err.contains("cancelled") && cancel.looked() == 2, "{err}, looked {}", cancel.looked()); + } + + /// 540 × 432 padded cells: each pass is three or four blocks. + #[test] + fn the_same_on_one_thread_and_several() { + let r = dem(400, 300, |c, rr| 700.0 + 80.0 * (c / 9.0).sin() * (rr / 6.0).cos() + c * 3.0); + let one = texture_on(Some(1), &r, 0, 0.5).unwrap(); + let many = texture_on(Some(4), &r, 0, 0.5).unwrap(); + assert_eq!(one.iter().map(|v| v.to_bits()).collect::>(), many.iter().map(|v| v.to_bits()).collect::>()); + } +}