├── .clang-format ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── LICENSE ├── README.md ├── cdt_bindings.cpp ├── cdt_bindings_test.py ├── pyproject.toml ├── requirements.txt └── setup.py /.clang-format: -------------------------------------------------------------------------------- 1 | # ================================ 2 | # Can be used when needed locally: 3 | # ================================ 4 | SortIncludes: false 5 | SortUsingDeclarations: true 6 | 7 | AccessModifierOffset: -4 8 | AlignAfterOpenBracket: AlwaysBreak 9 | AllowAllParametersOfDeclarationOnNextLine: false 10 | AllowShortBlocksOnASingleLine: false 11 | AllowShortCaseLabelsOnASingleLine: false 12 | AllowShortFunctionsOnASingleLine: None 13 | AllowShortIfStatementsOnASingleLine: false 14 | AllowShortLoopsOnASingleLine: false 15 | AlwaysBreakTemplateDeclarations: true 16 | BinPackArguments: false 17 | BinPackParameters: false 18 | BreakConstructorInitializersBeforeComma: true 19 | ColumnLimit: 80 20 | ConstructorInitializerIndentWidth: 4 21 | ContinuationIndentWidth: 4 22 | DerivePointerAlignment: false 23 | PointerAlignment: Left 24 | IndentWidth: 4 25 | Language: Cpp 26 | NamespaceIndentation: None 27 | SpaceBeforeParens: ControlStatements 28 | SpacesBeforeTrailingComments: 1 29 | Standard: Cpp03 30 | UseTab: Never 31 | 32 | # ===================== 33 | # Clang 5 new features: 34 | # ===================== 35 | BreakBeforeBraces: Custom 36 | BraceWrapping: 37 | AfterClass: true 38 | AfterControlStatement: true 39 | AfterEnum : true 40 | AfterFunction : true 41 | AfterNamespace : true 42 | AfterStruct : true 43 | AfterUnion : true 44 | BeforeCatch : true 45 | BeforeElse : true 46 | IndentBraces : false 47 | SplitEmptyFunction: false 48 | SplitEmptyRecord: false 49 | SplitEmptyNamespace: true 50 | BreakBeforeInheritanceComma: true 51 | FixNamespaceComments: true 52 | ReflowComments: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .cache/* 2 | .vscode/* 3 | .idea/* 4 | build/* 5 | cmake-build-*/* 6 | python/.venv/* 7 | .venv/* 8 | out/ 9 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "CDT"] 2 | path = CDT 3 | url = https://github.com/artem-ogre/CDT.git 4 | [submodule "pybind11"] 5 | path = pybind11 6 | url = https://github.com/pybind/pybind11.git 7 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.13.0) 2 | 3 | set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) 4 | 5 | project( 6 | PythonCDT 7 | VERSION 0.1.0 8 | DESCRIPTION "Software surface data rasterizer library" 9 | LANGUAGES CXX 10 | ) 11 | 12 | set(CMAKE_CXX_STANDARD 17) 13 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 14 | 15 | add_subdirectory(CDT/CDT CDT) 16 | add_subdirectory(pybind11) 17 | pybind11_add_module(PythonCDT cdt_bindings.cpp) 18 | target_include_directories( 19 | PythonCDT PRIVATE $ 20 | ) 21 | target_link_libraries(PythonCDT PRIVATE CDT::CDT) 22 | # Use rasterizer as pre-compiled header for faster test-only re-compiles 23 | #target_precompile_headers(PythonCDT PRIVATE include/rasterizer.h) 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonCDT 2 | 3 | Python bindings for [CDT: C++ library for constrained Delaunay triangulation](https://github.com/artem-ogre/CDT) implemented with [pybind11](https://github.com/pybind/pybind11) 4 | 5 | ***If PythonCDT helped you please consider adding a star on [GitHub](https://github.com/artem-ogre/PythonCDT). This means a lot to the authors*** 🤩 6 | ## Building 7 | 8 | ### Pre-conditions 9 | - Clone with submodules: `git clone --recurse-submodules https://github.com/artem-ogre/PythonCDT.git` 10 | - Make sure packages from requirements.txt are available. 11 | 12 | ```bash 13 | # build the wheel and install the package with pip 14 | pip3 install . 15 | # run tests 16 | pytest ./cdt_bindings_test.py 17 | ``` 18 | 19 | ## License 20 | [Mozilla Public License, v. 2.0](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) 21 | 22 | ## Contributors 23 | - [SioulisChris](https://github.com/SioulisChris): fixing the tests on Windows 24 | -------------------------------------------------------------------------------- /cdt_bindings.cpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | namespace py = pybind11; 19 | 20 | using coord_t = double; 21 | using NearPointLocator_t = CDT::LocatorKDTree; 22 | using V2d = CDT::V2d; 23 | using Triangulation = CDT::Triangulation; 24 | 25 | namespace 26 | { 27 | 28 | std::string TriInd2str(CDT::TriInd it) 29 | { 30 | return it != CDT::noNeighbor ? std::to_string(it) : "-"; 31 | } 32 | 33 | } // namespace 34 | 35 | PYBIND11_MODULE(PythonCDT, m) 36 | { 37 | // clang-format off 38 | m.doc() = R"pbdoc( 39 | PythonCDT module: python bindings for CDT: 40 | Constrained Delaunay Triangulation 41 | ----------------------- 42 | .. currentmodule:: PythonCDT 43 | .. autosummary:: 44 | :toctree: _generate 45 | )pbdoc"; 46 | // clang-format on 47 | 48 | #ifdef VERSION_INFO 49 | m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); 50 | #else 51 | m.attr("__version__") = "dev"; 52 | #endif 53 | 54 | m.attr("NO_NEIGHBOR") = py::int_(CDT::noNeighbor); 55 | m.attr("NO_VERTEX") = py::int_(CDT::noVertex); 56 | 57 | py::enum_(m, "VertexInsertionOrder") 58 | .value("AUTO", CDT::VertexInsertionOrder::Auto) 59 | .value("AS_PROVIDED", CDT::VertexInsertionOrder::AsProvided); 60 | 61 | py::enum_( 62 | m, "IntersectingConstraintEdges") 63 | .value("NOT_ALLOWED", CDT::IntersectingConstraintEdges::NotAllowed) 64 | .value("TRY_RESOLVE", CDT::IntersectingConstraintEdges::TryResolve) 65 | .value("DONT_CHECK", CDT::IntersectingConstraintEdges::DontCheck); 66 | 67 | py::class_(m, "V2d", py::buffer_protocol()) 68 | .def(py::init(), py::arg("x"), py::arg("y")) 69 | .def(py::init([](py::buffer b) { 70 | // Request a buffer descriptor from Python 71 | py::buffer_info info = b.request(); 72 | // Some sanity checks ... 73 | if (info.format != py::format_descriptor::format()) 74 | throw std::runtime_error( 75 | "Incompatible format: expected a double array!"); 76 | if (info.ndim != 1) 77 | throw std::runtime_error("Incompatible buffer dimension!"); 78 | // create from buffer 79 | const coord_t* const ptr = static_cast(info.ptr); 80 | return V2d{ptr[0], ptr[1]}; 81 | })) 82 | .def_readwrite("x", &V2d::x) 83 | .def_readwrite("y", &V2d::y) 84 | .def( 85 | "__eq__", 86 | [](const V2d& lhs, const V2d& rhs) { 87 | return lhs.x == rhs.x && lhs.y == rhs.y; 88 | }) 89 | .def( 90 | "__repr__", 91 | [](const V2d& v) { 92 | std::ostringstream oss; 93 | oss << "V2d(" << v.x << ", " << v.y << ")"; 94 | return oss.str(); 95 | }) 96 | .def_buffer([](V2d& v) -> py::buffer_info { 97 | return py::buffer_info( 98 | &v, 99 | sizeof(coord_t), 100 | py::format_descriptor::format(), 101 | 1, 102 | {2}, 103 | {sizeof(coord_t) * 2}); 104 | }); 105 | PYBIND11_NUMPY_DTYPE(V2d, x, y); 106 | 107 | PYBIND11_NUMPY_DTYPE(CDT::Triangle, vertices, neighbors); 108 | py::class_(m, "Triangle") 109 | .def_readwrite("vertices", &CDT::Triangle::vertices) 110 | .def_readwrite("neighbors", &CDT::Triangle::neighbors) 111 | .def( 112 | "__eq__", 113 | [](const CDT::Triangle& lhs, const CDT::Triangle& rhs) { 114 | return std::equal( 115 | std::begin(lhs.vertices), 116 | std::end(lhs.vertices), 117 | std::begin(rhs.vertices)) && 118 | std::equal( 119 | std::begin(lhs.neighbors), 120 | std::end(lhs.neighbors), 121 | std::begin(rhs.neighbors)); 122 | }) 123 | .def("__repr__", [](const CDT::Triangle& tri) { 124 | std::ostringstream oss; 125 | const CDT::VerticesArr3 vv = tri.vertices; 126 | const CDT::VerticesArr3 nn = tri.neighbors; 127 | oss << "Triangle(vertices(" << vv[0] << ", " << vv[1] << ", " 128 | << vv[2] << "), neighbors(" << TriInd2str(nn[0]) << ", " 129 | << TriInd2str(nn[1]) << ", " << TriInd2str(nn[2]) << "))"; 130 | return oss.str(); 131 | }); 132 | 133 | py::class_(m, "Edge", py::buffer_protocol()) 134 | .def( 135 | py::init(), 136 | py::arg("index_vert_a"), 137 | py::arg("index_vert_b")) 138 | .def(py::init([](py::buffer b) { 139 | // Request a buffer descriptor from Python 140 | py::buffer_info info = b.request(); 141 | // Some sanity checks ... 142 | if (info.format != py::format_descriptor::format()) 143 | throw std::runtime_error( 144 | "Incompatible format: expected a CDT::VertInd array!"); 145 | if (info.ndim != 1) 146 | throw std::runtime_error("Incompatible buffer dimension!"); 147 | // create from buffer 148 | const CDT::VertInd* const ptr = 149 | static_cast(info.ptr); 150 | return CDT::Edge(ptr[0], ptr[1]); 151 | })) 152 | .def_buffer([](CDT::Edge& e) -> py::buffer_info { 153 | return py::buffer_info( 154 | &e, 155 | sizeof(CDT::VertInd), 156 | py::format_descriptor::format(), 157 | 1, 158 | {2}, 159 | {sizeof(CDT::VertInd) * 2}); 160 | }) 161 | .def_property_readonly("v1", &CDT::Edge::v1) 162 | .def_property_readonly("v2", &CDT::Edge::v2) 163 | .def(py::self == py::self) 164 | .def(py::self != py::self) 165 | .def(py::hash(py::self)) 166 | .def("__repr__", [](const CDT::Edge& e) { 167 | std::ostringstream oss; 168 | oss << "Edge(" << e.v1() << ", " << e.v2() << ")"; 169 | return oss.str(); 170 | }); 171 | 172 | py::class_(m, "Triangulation") 173 | .def( 174 | py::init< 175 | CDT::VertexInsertionOrder::Enum, 176 | CDT::IntersectingConstraintEdges::Enum, 177 | coord_t>(), 178 | py::arg("vertex_insertion_order"), 179 | py::arg("intersecting_edges_strategy"), 180 | py::arg("min_dist_to_constraint_edge")) 181 | // vertices 182 | .def_readonly("vertices", &Triangulation::vertices) 183 | .def( 184 | "vertices_count", 185 | [](const Triangulation& t) { return t.vertices.size(); }) 186 | .def( 187 | "vertices_iter", 188 | [](const Triangulation& t) -> py::iterator { 189 | return py::make_iterator(t.vertices.begin(), t.vertices.end()); 190 | }, 191 | py::keep_alive<0, 1>()) 192 | // triangles 193 | .def_readonly("triangles", &Triangulation::triangles) 194 | .def( 195 | "triangles_count", 196 | [](const Triangulation& t) { return t.triangles.size(); }) 197 | .def( 198 | "triangles_iter", 199 | [](const Triangulation& t) -> py::iterator { 200 | return py::make_iterator( 201 | t.triangles.begin(), t.triangles.end()); 202 | }, 203 | py::keep_alive<0, 1>()) 204 | // fixed edges 205 | .def_readonly("fixed_edges", &Triangulation::fixedEdges) 206 | .def( 207 | "fixed_edges_count", 208 | [](const Triangulation& t) { return t.fixedEdges.size(); }) 209 | .def( 210 | "fixed_edges_iter", 211 | [](const Triangulation& t) -> py::iterator { 212 | return py::make_iterator( 213 | t.fixedEdges.begin(), t.fixedEdges.end()); 214 | }, 215 | py::keep_alive<0, 1>()) 216 | // overlaps 217 | .def_readonly("overlap_count", &Triangulation::overlapCount) 218 | .def( 219 | "overlap_count_count", 220 | [](const Triangulation& t) { return t.overlapCount.size(); }) 221 | .def( 222 | "overlap_count_iter", 223 | [](const Triangulation& t) -> py::iterator { 224 | return py::make_iterator( 225 | t.overlapCount.begin(), t.overlapCount.end()); 226 | }, 227 | py::keep_alive<0, 1>()) 228 | // piece to originals mapping for edges 229 | .def_readonly("piece_to_originals", &Triangulation::pieceToOriginals) 230 | .def( 231 | "piece_to_originals_count", 232 | [](const Triangulation& t) { return t.pieceToOriginals.size(); }) 233 | .def( 234 | "piece_to_originals_iter", 235 | [](const Triangulation& t) -> py::iterator { 236 | return py::make_iterator( 237 | t.pieceToOriginals.begin(), t.pieceToOriginals.end()); 238 | }, 239 | py::keep_alive<0, 1>()) 240 | // methods 241 | .def( 242 | "insert_vertices", 243 | static_cast&)>( 244 | &Triangulation::insertVertices), 245 | py::arg("vertices")) 246 | .def( 247 | "insert_vertices", 248 | [](Triangulation& t, py::buffer b) { 249 | const py::buffer_info info = b.request(); 250 | // sanity checks 251 | if (info.format != py::format_descriptor::format()) 252 | { 253 | throw std::runtime_error( 254 | "Incompatible format: expected a double array!"); 255 | } 256 | if (info.ndim != 1 && info.ndim != 2) 257 | { 258 | throw std::runtime_error("Incompatible buffer dimension!"); 259 | } 260 | if (info.size % 2 != 0) 261 | { 262 | throw std::runtime_error("Buffer must hold even number of " 263 | "coordinates (2 per vertex)!"); 264 | } 265 | // create from buffer 266 | struct XY 267 | { 268 | coord_t xy[2]; 269 | }; 270 | const std::size_t n_vert = info.size / 2; 271 | const XY* const ptr = static_cast(info.ptr); 272 | t.insertVertices( 273 | ptr, 274 | ptr + n_vert, 275 | [](const XY& v) { return v.xy[0]; }, 276 | [](const XY& v) { return v.xy[1]; }); 277 | }, 278 | py::arg("vertex_buffer")) 279 | .def( 280 | "insert_edges", 281 | static_cast&)>( 282 | &Triangulation::insertEdges), 283 | py::arg("edges")) 284 | .def( 285 | "insert_edges", 286 | [](Triangulation& t, py::buffer b) { 287 | const py::buffer_info info = b.request(); 288 | // sanity checks 289 | if (info.format != 290 | py::format_descriptor::format()) 291 | { 292 | throw std::runtime_error( 293 | "Incompatible format: expected a CDT::VertInd array!"); 294 | } 295 | if (info.ndim != 1 && info.ndim != 2) 296 | { 297 | throw std::runtime_error("Incompatible buffer dimension!"); 298 | } 299 | if (info.size % 2 != 0) 300 | { 301 | throw std::runtime_error("Buffer must hold even number of " 302 | "CDT::VertInd (2 per edge)!"); 303 | } 304 | // create from buffer 305 | struct EdgeData 306 | { 307 | CDT::VertInd vv[2]; 308 | }; 309 | const std::size_t n_vert = info.size / 2; 310 | const EdgeData* const ptr = static_cast(info.ptr); 311 | t.insertEdges( 312 | ptr, 313 | ptr + n_vert, 314 | [](const EdgeData& e) { return e.vv[0]; }, 315 | [](const EdgeData& e) { return e.vv[1]; }); 316 | }, 317 | py::arg("edge_buffer")) 318 | .def( 319 | "conform_to_edges", 320 | static_cast&)>( 321 | &Triangulation::conformToEdges), 322 | py::arg("edges")) 323 | .def( 324 | "conform_to_edges", 325 | [](Triangulation& t, py::buffer b) { 326 | const py::buffer_info info = b.request(); 327 | // sanity checks 328 | if (info.format != 329 | py::format_descriptor::format()) 330 | { 331 | throw std::runtime_error( 332 | "Incompatible format: expected a CDT::VertInd array!"); 333 | } 334 | if (info.ndim != 1 && info.ndim != 2) 335 | { 336 | throw std::runtime_error("Incompatible buffer dimension!"); 337 | } 338 | if (info.size % 2 != 0) 339 | { 340 | throw std::runtime_error("Buffer must hold even number of " 341 | "CDT::VertInd (2 per edge)!"); 342 | } 343 | // create from buffer 344 | struct EdgeData 345 | { 346 | CDT::VertInd vv[2]; 347 | }; 348 | const std::size_t n_vert = info.size / 2; 349 | const EdgeData* const ptr = static_cast(info.ptr); 350 | t.conformToEdges( 351 | ptr, 352 | ptr + n_vert, 353 | [](const EdgeData& e) { return e.vv[0]; }, 354 | [](const EdgeData& e) { return e.vv[1]; }); 355 | }, 356 | py::arg("edge_buffer")) 357 | .def("erase_super_triangle", &Triangulation::eraseSuperTriangle) 358 | .def("erase_outer_triangles", &Triangulation::eraseOuterTriangles) 359 | .def( 360 | "erase_outer_triangles_and_holes", 361 | &Triangulation::eraseOuterTrianglesAndHoles) 362 | .def("is_finalized", &Triangulation::isFinalized) 363 | .def( 364 | "calculate_triangle_depths", 365 | &Triangulation::calculateTriangleDepths) 366 | .def( 367 | "remove_triangles", 368 | static_cast( 369 | &Triangulation::removeTriangles), 370 | py::arg("triangle_indices")); 371 | 372 | m.def( 373 | "verify_topology", 374 | &CDT::verifyTopology, 375 | py::arg("triangulation")); 376 | } 377 | -------------------------------------------------------------------------------- /cdt_bindings_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # This Source Code Form is subject to the terms of the Mozilla Public 4 | # License, v. 2.0. If a copy of the MPL was not distributed with this 5 | # file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 | 7 | """ Tests for CDT Python bindings """ 8 | 9 | import numpy as np 10 | import pytest 11 | import tempfile 12 | import hashlib 13 | 14 | import PythonCDT as cdt 15 | 16 | 17 | def test_constants() -> None: 18 | """Test that constants have proper values""" 19 | assert cdt.NO_NEIGHBOR == np.iinfo(np.uintc).max, "NO_NEIGHBOR constant has wrong value" 20 | assert cdt.NO_VERTEX == np.iinfo(np.uintc).max, "NO_VERTEX constant has wrong value" 21 | 22 | 23 | def test_V2d() -> None: 24 | """Test 2D vector""" 25 | p = cdt.V2d(42, 42) 26 | assert p.x == 42 and p.y == 42, "Error in constructing 2D vector with int" 27 | p = cdt.V2d(42.0, 42.0) 28 | assert p.x == 42 and p.y == 42, "Error in constructing 2D vector with float" 29 | p = cdt.V2d(np.array([42., 42.])) 30 | assert p.x == 42 and p.y == 42, "Error in constructing 2D vector with buffer protocol" 31 | 32 | assert cdt.V2d(1.23, 2).__repr__() == "V2d(1.23, 2)", "Wrong __repr__ output for V2d" 33 | 34 | 35 | def test_Edge() -> None: 36 | """Test Edge class""" 37 | e = cdt.Edge(1, 2) 38 | assert e.v1 == 1 and e.v2 == 2, "Constructed wrong edge" 39 | e = cdt.Edge(2, 1) 40 | assert e.v1 == 1 and e.v2 == 2, "Constructed wrong edge" 41 | e = cdt.Edge(np.array([2, 1], dtype=np.uintc)) 42 | assert e.v1 == 1 and e.v2 == 2, "Constructed wrong edge" 43 | 44 | assert cdt.Edge(1, 2).__repr__() == "Edge(1, 2)", "Wrong __repr__ output for Edge" 45 | 46 | 47 | def test_Triangulation() -> None: 48 | """Test Triangulation class""" 49 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.NOT_ALLOWED, 0.0) 50 | assert len(t.vertices) == 0, "Wrong vertex count in empty triangulation" 51 | assert len(t.triangles) == 0, "Wrong triangle count in empty triangulation" 52 | assert len(t.fixed_edges) == 0, "Wrong fixed edge count in empty triangulation" 53 | 54 | vv = [cdt.V2d(-1, 0), cdt.V2d(0, 0.5), cdt.V2d(1, 0), cdt.V2d(0, -0.5)] 55 | t.insert_vertices(vv) 56 | assert len(t.vertices) == 7, "Wrong vertex count in triangulation" 57 | assert len(t.triangles) == 9, "Wrong triangle count in triangulation" 58 | assert len(t.fixed_edges) == 0, "Wrong fixed edge count in triangulation" 59 | 60 | ee = [cdt.Edge(0, 2)] 61 | t.insert_edges(ee) 62 | assert len(t.fixed_edges) == 1, "Wrong fixed edge count in triangulation" 63 | assert cdt.Edge(0 + 3, 2 + 3) in t.fixed_edges, "Constraint edge was not properly added" 64 | 65 | t.erase_super_triangle() 66 | assert cdt.Edge(0, 2) in t.fixed_edges, "Constraint edge was not properly added" 67 | assert len(t.vertices) == 4, "Wrong vertex count in triangulation" 68 | assert len(t.triangles) == 2, "Wrong triangle count in triangulation" 69 | assert len(t.fixed_edges) == 1, "Wrong fixed edge count in triangulation" 70 | 71 | # test retrieving triangulation data using iterators 72 | assert t.vertices_count() == len(t.vertices), "Wrong vertex count" 73 | assert t.triangles_count() == len(t.triangles), "Wrong triangle count" 74 | assert t.fixed_edges_count() == len(t.fixed_edges), "Wrong fixed edge count" 75 | assert t.overlap_count_count() == len(t.overlap_count), "Wrong number of overlap-count" 76 | assert t.piece_to_originals_count() == len(t.piece_to_originals), "Wrong piece-to-originals count" 77 | for i, v in enumerate(t.vertices_iter()): 78 | assert v == t.vertices[i], "Wrong vertex from iterable" 79 | for i, tri in enumerate(t.triangles_iter()): 80 | assert tri == t.triangles[i], "Wrong triangle from iterable" 81 | for fe in t.fixed_edges_iter(): 82 | assert fe in t.fixed_edges, "Wrong fixed edges from iterable" 83 | for key, val in t.overlap_count_iter(): 84 | assert t.overlap_count[key] == val, "Wrong overlap-count from iterable" 85 | for key, val in t.piece_to_originals_iter(): 86 | assert t.piece_to_originals[key] == val, "Wrong piece-to-originals from iterable" 87 | 88 | # Test resolving fixed edge intersections 89 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.TRY_RESOLVE, 0.0) 90 | ee = [cdt.Edge(0, 2), cdt.Edge(1, 3)] 91 | t.insert_vertices(vv) 92 | t.insert_edges(ee) 93 | t.erase_super_triangle() 94 | assert len(t.vertices) == 5, "Wrong vertex count in triangulation" 95 | assert len(t.triangles) == 4, "Wrong triangle count in triangulation" 96 | 97 | 98 | def test_verify_topology() -> None: 99 | """Test verifying CDT topology""" 100 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.TRY_RESOLVE, 0.0) 101 | t.insert_vertices([cdt.V2d(-1, 0), cdt.V2d(0, 0.5), cdt.V2d(1, 0), cdt.V2d(0, -0.5)]) 102 | t.insert_edges([cdt.Edge(0, 2), cdt.Edge(1, 3)]) 103 | assert cdt.verify_topology(t), "Verifying topology produced wrong result" 104 | 105 | 106 | def save_triangulation_as_off(t: cdt.Triangulation, off_file) -> None: 107 | with open(off_file, "w") as f: 108 | f.write(f"OFF\n") 109 | f.write(f"{t.vertices_count()} {t.triangles_count()} 0\n") 110 | for v in t.vertices_iter(): 111 | f.write(f"{v.x} {v.y} 0\n") 112 | for tri in t.triangles_iter(): 113 | vv = tri.vertices 114 | f.write(f"3 {int(vv[0])} {int(vv[1])} {int(vv[2])}\n") 115 | 116 | 117 | def read_input_file(input_file): 118 | with open(input_file, "r") as f: 119 | n_verts, n_edges = (int(s) for s in f.readline().split()) 120 | verts = [cdt.V2d(*(float(s) for s in f.readline().split())) for _ in range(n_verts)] 121 | edges = [cdt.Edge(*(int(s) for s in f.readline().split())) for _ in range(n_edges)] 122 | return verts, edges 123 | 124 | def md5_checksum(file_path): 125 | with open(file_path, 'r') as f: 126 | return hashlib.md5(f.read().encode('utf-8')).hexdigest() 127 | 128 | def triangulation_md5_checksum(t: cdt.Triangulation): 129 | with tempfile.TemporaryDirectory() as tmp_dir: 130 | off_file = f"{tmp_dir}/cdt.off" 131 | save_triangulation_as_off(t, off_file) 132 | return md5_checksum(off_file) 133 | 134 | def test_triangulate_input_file() -> None: 135 | vv, ee = read_input_file("CDT/visualizer/data/Constrained Sweden.txt") 136 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.TRY_RESOLVE, 0.0) 137 | t.insert_vertices(vv) 138 | t.insert_edges(ee) 139 | t.erase_outer_triangles_and_holes() 140 | with tempfile.TemporaryDirectory() as tmp_dir: 141 | off_file = f"{tmp_dir}/cdt.off" 142 | save_triangulation_as_off(t, off_file) 143 | assert md5_checksum(off_file) == '5fb163a9f27ec6bdd05b7d5f2b23416c', "Wrong OFF file contents" 144 | 145 | 146 | def test_conform_to_edges() -> None: 147 | vv, ee = read_input_file("CDT/visualizer/data/ditch.txt") 148 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.TRY_RESOLVE, 0.0) 149 | t.insert_vertices(vv) 150 | t.conform_to_edges(ee) 151 | t.erase_outer_triangles_and_holes() 152 | assert triangulation_md5_checksum(t) == 'df2503c614e2f98656038948b355b27e', "Wrong OFF file contents" 153 | 154 | 155 | @pytest.mark.parametrize("vv", [[cdt.V2d(-1, 0), cdt.V2d(0, 0.5), cdt.V2d(1, 0), cdt.V2d(0, -0.5)], 156 | np.array([[-1, 0], [0, 0.5], [1, 0], [0, -0.5]], dtype=np.float64), 157 | np.array([-1, 0, 0, 0.5, 1, 0, 0, -0.5], dtype=np.float64)]) 158 | def test_insert_vertices(vv) -> None: 159 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.NOT_ALLOWED, 0.0) 160 | t.insert_vertices(vv) 161 | assert len(t.vertices) == 7, "Wrong vertex count in triangulation" 162 | assert len(t.triangles) == 9, "Wrong triangle count in triangulation" 163 | assert len(t.fixed_edges) == 0, "Wrong fixed edge count in triangulation" 164 | assert triangulation_md5_checksum(t) == 'c424c4f2691dc3b9aabd39dcf2e17c53', "Wrong OFF file contents" 165 | 166 | 167 | @pytest.mark.parametrize("ee", [[cdt.Edge(0, 1), cdt.Edge(2, 3), cdt.Edge(3, 4), cdt.Edge(5, 6)], 168 | np.array([[0, 1], [2, 3], [3, 4], [5, 6]], dtype=np.uintc), 169 | np.array([0, 1, 2, 3, 3, 4, 5, 6], dtype=np.uintc)]) 170 | def test_insert_conform_edges(ee) -> None: 171 | # insert edges 172 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.NOT_ALLOWED, 0.0) 173 | t.insert_vertices(np.array([[0, 0], [4, 0], [5, 1], [2, 1], [-1, 1], [0, 2], [4, 2]], dtype=float)) 174 | t.insert_edges(ee) 175 | assert len(t.vertices) == 10, "Wrong vertex count in triangulation" 176 | assert len(t.triangles) == 15, "Wrong triangle count in triangulation" 177 | assert len(t.fixed_edges) == 4, "Wrong fixed edge count in triangulation" 178 | assert triangulation_md5_checksum(t) == '8424ba2c8f8ebabe1bea4141464a347b', "Wrong OFF file contents" 179 | 180 | # conform to edges 181 | t = cdt.Triangulation(cdt.VertexInsertionOrder.AS_PROVIDED, cdt.IntersectingConstraintEdges.NOT_ALLOWED, 0.0) 182 | t.insert_vertices(np.array([[0, 0], [4, 0], [5, 1], [2, 1], [-1, 1], [0, 2], [4, 2]], dtype=float)) 183 | t.conform_to_edges(ee) 184 | assert len(t.vertices) == 12, "Wrong vertex count in triangulation" 185 | assert len(t.triangles) == 19, "Wrong triangle count in triangulation" 186 | assert len(t.fixed_edges) == 6, "Wrong fixed edge count in triangulation" 187 | assert triangulation_md5_checksum(t) == '9cb9dbaca4943ff0e3aab6c1d31f5a35', "Wrong OFF file contents" 188 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel", 5 | "ninja", 6 | "cmake>=3.12", 7 | ] 8 | build-backend = "setuptools.build_meta" 9 | 10 | [tool.isort] 11 | profile = "black" 12 | 13 | [tool.pytest.ini_options] 14 | minversion = "6.0" 15 | addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"] 16 | xfail_strict = true 17 | filterwarnings = ["error"] 18 | testpaths = ["tests"] 19 | 20 | [tool.cibuildwheel] 21 | test-command = "pytest {project}/tests" 22 | test-extras = ["test"] 23 | test-skip = ["*universal2:arm64"] 24 | # Setuptools bug causes collision between pypy and cpython artifacts 25 | before-build = "rm -rf {project}/build" 26 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | pytest -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import subprocess 4 | import sys 5 | 6 | from setuptools import Extension, setup 7 | from setuptools.command.build_ext import build_ext 8 | 9 | # Convert distutils Windows platform specifiers to CMake -A arguments 10 | PLAT_TO_CMAKE = { 11 | "win32": "Win32", 12 | "win-amd64": "x64", 13 | "win-arm32": "ARM", 14 | "win-arm64": "ARM64", 15 | } 16 | 17 | 18 | # A CMakeExtension needs a sourcedir instead of a file list. 19 | # The name must be the _single_ output extension from the CMake build. 20 | # If you need multiple extensions, see scikit-build. 21 | class CMakeExtension(Extension): 22 | def __init__(self, name, sourcedir=""): 23 | Extension.__init__(self, name, sources=[]) 24 | self.sourcedir = os.path.abspath(sourcedir) 25 | 26 | 27 | class CMakeBuild(build_ext): 28 | def build_extension(self, ext): 29 | extdir = os.path.abspath(os.path.dirname( 30 | self.get_ext_fullpath(ext.name))) 31 | 32 | # required for auto-detection & inclusion of auxiliary "native" libs 33 | if not extdir.endswith(os.path.sep): 34 | extdir += os.path.sep 35 | 36 | debug = int(os.environ.get("DEBUG", 0) 37 | ) if self.debug is None else self.debug 38 | cfg = "Debug" if debug else "Release" 39 | 40 | # CMake lets you override the generator - we need to check this. 41 | # Can be set with Conda-Build, for example. 42 | cmake_generator = os.environ.get("CMAKE_GENERATOR", "") 43 | 44 | # Set Python_EXECUTABLE instead if you use PYBIND11_FINDPYTHON 45 | # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code 46 | # from Python. 47 | cmake_args = [ 48 | f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}", 49 | f"-DPYTHON_EXECUTABLE={sys.executable}", 50 | f"-DCMAKE_BUILD_TYPE={cfg}", # not used on MSVC, but no harm 51 | ] 52 | build_args = [] 53 | # Adding CMake arguments set as environment variable 54 | # (needed e.g. to build for ARM OSx on conda-forge) 55 | if "CMAKE_ARGS" in os.environ: 56 | cmake_args += [ 57 | item for item in os.environ["CMAKE_ARGS"].split(" ") if item] 58 | 59 | # In this example, we pass in the version to C++. You might not need to. 60 | cmake_args += [ 61 | f"-DEXAMPLE_VERSION_INFO={self.distribution.get_version()}"] 62 | 63 | if self.compiler.compiler_type != "msvc": 64 | # Using Ninja-build since it a) is available as a wheel and b) 65 | # multithreads automatically. MSVC would require all variables be 66 | # exported for Ninja to pick it up, which is a little tricky to do. 67 | # Users can override the generator with CMAKE_GENERATOR in CMake 68 | # 3.15+. 69 | if not cmake_generator: 70 | try: 71 | import ninja # noqa: F401 72 | 73 | cmake_args += ["-GNinja"] 74 | except ImportError: 75 | pass 76 | 77 | else: 78 | 79 | # Single config generators are handled "normally" 80 | single_config = any( 81 | x in cmake_generator for x in {"NMake", "Ninja"}) 82 | 83 | # CMake allows an arch-in-generator style for backward compatibility 84 | contains_arch = any(x in cmake_generator for x in {"ARM", "Win64"}) 85 | 86 | # Specify the arch if using MSVC generator, but only if it doesn't 87 | # contain a backward-compatibility arch spec already in the 88 | # generator name. 89 | if not single_config and not contains_arch: 90 | cmake_args += ["-A", PLAT_TO_CMAKE[self.plat_name]] 91 | 92 | # Multi-config generators have a different way to specify configs 93 | if not single_config: 94 | cmake_args += [ 95 | f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg.upper()}={extdir}" 96 | ] 97 | build_args += ["--config", cfg] 98 | 99 | if sys.platform.startswith("darwin"): 100 | # Cross-compile support for macOS - respect ARCHFLAGS if set 101 | archs = re.findall(r"-arch (\S+)", os.environ.get("ARCHFLAGS", "")) 102 | if archs: 103 | cmake_args += [ 104 | "-DCMAKE_OSX_ARCHITECTURES={}".format(";".join(archs))] 105 | 106 | # Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level 107 | # across all generators. 108 | if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ: 109 | # self.parallel is a Python 3 only way to set parallel jobs by hand 110 | # using -j in the build_ext call, not supported by pip or PyPA-build. 111 | if hasattr(self, "parallel") and self.parallel: 112 | # CMake 3.12+ only. 113 | build_args += [f"-j{self.parallel}"] 114 | 115 | if not os.path.exists(self.build_temp): 116 | os.makedirs(self.build_temp) 117 | 118 | subprocess.check_call( 119 | ["cmake", ext.sourcedir] + cmake_args, cwd=self.build_temp 120 | ) 121 | subprocess.check_call( 122 | ["cmake", "--build", "."] + build_args, cwd=self.build_temp 123 | ) 124 | 125 | 126 | # The information here can also be placed in setup.cfg - better separation of 127 | # logic and declaration, and simpler if you include description/version in a file. 128 | setup( 129 | name="PythonCDT", 130 | version="0.0.1", 131 | author="Leica Geosystems", 132 | author_email="", 133 | description="Test", 134 | long_description="", 135 | ext_modules=[CMakeExtension("PythonCDT")], 136 | cmdclass={"build_ext": CMakeBuild}, 137 | zip_safe=False, 138 | extras_require={"test": ["pytest>=6.0"]}, 139 | python_requires=">=3.6", 140 | ) 141 | --------------------------------------------------------------------------------