├── LICENSE ├── README.md ├── __init__.py ├── blender_utils.py ├── blockBuilder.py ├── blockMeshBodyFit.py ├── blockMeshMG.py ├── cycleFinderNumba.py └── utils.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwiftBlock 2 | Blender addon for creating blockMeshDict files for OpenFOAM's blockMesh application. Compatible with Blender 3D 2.76 ->, OpenFOAM 5.0 -> and NumPy 1.13-> 3 | 4 | ## New features: 5 | * The SwiftBlock panel has moved from the properties panel to the tools panel 6 | * The block structure is saved and therefore the time consuming block detection algorithm is only required when the block structure is changed 7 | * The blocks are listed in the SwiftBlock panel 8 | * Blocks can be selected, disabled and enabled interactively from the list 9 | * Blocks can be searched from the current mesh selection 10 | * Number of cells are defined instead of the maximum cell size 11 | * The parallel edges of an edge can be selected easily 12 | * The edge directions visualization 13 | * The new projection vertices, edges and faces to surfaces has been implemented 14 | * The projections are listed in the panel 15 | * The projections can be selected and removed from the list 16 | * Show/hide internal faces to make projections on them 17 | * The automatic snapping algorithm can also be selected 18 | * Extrude blocks operator which preserves internal edges and faces (ALT+E opens the extrude menu) 19 | * Faster block detection with Numba 20 | 21 | ## How to install Blender, NumPy and SwiftBlock on Ubuntu 22 | ```bash 23 | sudo apt install blender 24 | sudo apt install python3-pip 25 | pip3 install numpy 26 | mkdir -p $HOME/.config/blender/2.xx/scripts/addons 27 | cd $HOME/.config/blender/2.xx/scripts/addons 28 | git clone https://github.com/flowkersma/swiftBlock/ 29 | ``` 30 | Replace 2.xx with your Blender version. Load your OpenFOAM environment and launch Blender. In Blender open the preferences (File->User Preferences). Click on addons tab, search for SwiftBlock and enable it. 31 | 32 | Happy meshing! 33 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | bl_info = { 2 | "name": "SwiftBlock", 3 | "author": "Karl-Johan Nogenmyr, Mikko Folkersma, Turo Valikangas", 4 | "version": (0, 2), 5 | "blender": (2, 7, 7), 6 | "location": "View_3D > Object > SwiftBlock", 7 | "description": "Writes block geometry as blockMeshDict file", 8 | "warning": "", 9 | "wiki_url": "http://openfoamwiki.net/index.php/SwiftBlock", 10 | "tracker_url": "", 11 | "category": "OpenFOAM"} 12 | 13 | import bpy 14 | import bmesh 15 | import time 16 | import importlib 17 | from . import blockBuilder 18 | importlib.reload(blockBuilder) 19 | from . import blender_utils 20 | importlib.reload(blender_utils) 21 | from . import utils 22 | importlib.reload(utils) 23 | from mathutils import Vector 24 | 25 | 26 | # Create the swiftBlock panel 27 | class SwiftBlockPanel(bpy.types.Panel): 28 | bl_space_type = "VIEW_3D" 29 | bl_region_type = "TOOLS" 30 | bl_category = "SwiftBlock" 31 | bl_label = "SwiftBlock" 32 | 33 | def draw(self, context): 34 | scn = context.scene 35 | ob = context.active_object 36 | if not ob: 37 | return 38 | box = self.layout.column(align=True) 39 | 40 | if ob.ispreviewObject: 41 | box = self.layout.box() 42 | box.operator("activate.blocking", text="Activate blocking").hide = True 43 | elif ob.blocking_object and ob.name != ob.blocking_object: 44 | box = self.layout.box() 45 | box.operator("activate.blocking", text="Activate blocking").hide = False 46 | elif not ob.isblockingObject and ob.type == 'MESH': 47 | box.operator("init.blocking", text="Initialize blocking") 48 | 49 | elif context.active_object and bpy.context.active_object.mode == "EDIT": 50 | 51 | box = self.layout.box() 52 | box.prop(ob,"Mesher") 53 | split = box.split(percentage=0.5) 54 | split.operator("build.blocking", text="Build Blocking") 55 | split.prop(ob, "useNumba") 56 | 57 | split = box.split() 58 | split.operator("preview.mesh", text="Preview mesh") 59 | split = split.split() 60 | split.operator("write.mesh", text="Write mesh") 61 | box.template_list("block_items", "", ob, "blocks", ob, "block_index", rows=2) 62 | box.operator("get.block") 63 | 64 | box = self.layout.box() 65 | box.label("Edge mapping") 66 | # box.prop(ob, "MappingType") 67 | split = box.split() 68 | split.prop(ob, "Cells") 69 | # split.operator('set.cellsize') 70 | if ob.Mesher == "blockMeshMG": 71 | split = box.split() 72 | col = split.column() 73 | col.label("Start") 74 | col.prop(ob, "x1") 75 | col.prop(ob, "r1") 76 | col = split.column() 77 | col.label("End") 78 | col.prop(ob, "x2") 79 | col.prop(ob, "r2") 80 | elif ob.Mesher == "blockMeshBodyFit": 81 | split.prop(ob, "Ratio") 82 | split = box.split() 83 | split.operator("set.edgemapping") 84 | split.operator("get.edge") 85 | split = box.split() 86 | split.operator("select.parallel") 87 | split.operator("flip.edges") 88 | if 'Edge_directions' in bpy.data.objects: 89 | box.operator("draw.directions",'Show edge directions',emboss=False,icon="CHECKBOX_HLT").show=False 90 | else: 91 | box.operator("draw.directions",'Show edge directions',emboss=False,icon="CHECKBOX_DEHLT").show=True 92 | 93 | box = self.layout.box() 94 | box.label("Projections") 95 | split = box.split() 96 | split.prop(ob, "ProjectionObject","",icon = "OUTLINER_OB_SURFACE") 97 | split.operator("add.projections", text="Add") 98 | split.operator("remove.projections", text="Remove") 99 | if ob.Mesher == "blockMeshBodyFit": 100 | box.prop(ob, 'SearchLength') 101 | box.template_list("projection_items", "", ob, "projections", ob, "projection_index", rows=2) 102 | if ob.Autosnap: 103 | split = box.split(percentage=0.1) 104 | split.prop(ob, "Autosnap", "") 105 | split = split.split(percentage=0.9) 106 | split.prop(ob, "EdgeSnapObject",'') 107 | if ob.EdgeSnapObject != "": 108 | o = split.operator("activate.object","",emboss=False,icon="OBJECT_DATA") 109 | o.ob = ob.EdgeSnapObject 110 | else: 111 | box.prop(ob, "Autosnap") 112 | box.prop(ob,"ShowInternalFaces") 113 | 114 | 115 | box = self.layout.box() 116 | box.label('Boundary conditions') 117 | row = box.row() 118 | row.template_list("boundary_items", "", ob.data, "materials", ob, "boundary_index", rows=2) 119 | col = row.column(align=True) 120 | col.operator("boundaries.action", icon='ZOOMIN', text="").action = 'ADD' 121 | col.operator("boundaries.action", icon='ZOOMOUT', text="").action = 'REMOVE' 122 | row = self.layout.row() 123 | row.operator('boundaries.action', 'Assign').action = 'ASSIGN' 124 | 125 | def initSwiftBlockProperties(): 126 | bpy.types.Object.isblockingObject = bpy.props.BoolProperty(default=False) 127 | bpy.types.Object.blocking_object = bpy.props.StringProperty(default="") 128 | bpy.types.Object.ispreviewObject = bpy.props.BoolProperty(default=False) 129 | bpy.types.Object.preview_object = bpy.props.StringProperty(default='') 130 | bpy.types.Object.direction_object = bpy.props.StringProperty(default="") 131 | bpy.types.Object.isdirectionObject = bpy.props.BoolProperty(default=False) 132 | 133 | bpy.types.Object.Mesher = bpy.props.EnumProperty(name="", 134 | items = (("blockMeshMG","blockMeshMG","",1), 135 | ("blockMeshBodyFit","blockMeshBodyFit","",2),),update=changeMesher) 136 | 137 | 138 | # Blocking properties 139 | bpy.types.Object.blocks = \ 140 | bpy.props.CollectionProperty(type=BlockProperty) 141 | bpy.types.Object.block_index = bpy.props.IntProperty() 142 | bpy.types.Object.useNumba = bpy.props.BoolProperty(default=False, name="Use Numba?") 143 | 144 | 145 | # Projection/snapping properties 146 | bpy.types.Object.projections = \ 147 | bpy.props.CollectionProperty(type=ProjectionProperty) 148 | bpy.types.Object.projection_index = bpy.props.IntProperty() 149 | 150 | bpy.types.Object.Autosnap = bpy.props.BoolProperty(name="Automatic edge projection", 151 | description = "Snap lines automatically from geometry?") 152 | bpy.types.Object.ShowInternalFaces = bpy.props.BoolProperty(name="Show Internal Faces", 153 | default=False, update=showInternalFaces) 154 | bpy.types.Object.ProjectionObject = bpy.props.EnumProperty(name="Projection object", 155 | items=getProjectionObjects, description = "Projection object") 156 | bpy.types.Object.EdgeSnapObject = bpy.props.EnumProperty(name="Object", 157 | items=getProjectionObjects, description = "Projection object") 158 | 159 | # Mapping properties 160 | bpy.types.Object.MappingType = bpy.props.EnumProperty(name="", 161 | items = (("Geometric MG","Geometric MG","",1), 162 | ("Geometric","Geometric","",2),)) 163 | # bpy.types.Object.Dx = bpy.props.FloatProperty(name="dx", default=1, update=setCellSize, min=0) 164 | bpy.types.Object.Cells = bpy.props.IntProperty(name="Cells", default=10, min=1) 165 | bpy.types.Object.x1 = bpy.props.FloatProperty(name="x1", default=0, description="First cell size", min=0) 166 | bpy.types.Object.x2 = bpy.props.FloatProperty(name="x2", default=0, description="Last cell size", min=0) 167 | bpy.types.Object.r1 = bpy.props.FloatProperty(name="r1", default=1.2, description="First boundary layer geometric ratio", min=1.0) 168 | bpy.types.Object.r2 = bpy.props.FloatProperty(name="r2", default=1.2, description="Last boundary layer geometric ratio", min=1.0) 169 | bpy.types.Object.Ratio = bpy.props.FloatProperty(name="Ratio", default=1.0, description="Ratio of first cell to last cell", min=0) 170 | bpy.types.Object.SearchLength = bpy.props.FloatProperty(name="Search Length", default=1.0, description="", min=0) 171 | # bpy.types.Object.ShowEdgeDirections = bpy.props.BoolProperty(name="Show directions", default=True, update = updateEdgeDirections, description="Show edge directions?") 172 | 173 | # Boundary condition properties 174 | bpy.types.Object.bcTypeEnum = bpy.props.EnumProperty( 175 | items = [('wall', 'wall', 'Defines the patch as wall'), 176 | ('patch', 'patch', 'Defines the patch as generic patch'), 177 | ('empty', 'empty', 'Defines the patch as empty'), 178 | ('symmetry', 'symmetry', 'Defines the patch as symmetry'), 179 | ], 180 | name = "Patch type") 181 | 182 | bpy.types.Object.patchName = bpy.props.StringProperty( 183 | name = "Patch name", 184 | description = "Specify name of patch", 185 | default = "defaultName") 186 | 187 | bpy.types.Object.boundary_index = bpy.props.IntProperty(update=selectActiveBoundary) 188 | bpy.types.Material.boundary_type = bpy.props.EnumProperty( 189 | items = [('wall', 'wall',''), 190 | ('patch', 'patch',''), 191 | ('empty', 'empty',''), 192 | ('symmetry', 'symmetry',''), 193 | ], 194 | name = "Patch type") 195 | 196 | # Edge group properties 197 | bpy.types.Object.edge_groups = \ 198 | bpy.props.CollectionProperty(type=EdgeGroupProperty) 199 | bpy.types.Object.EdgeGroupName = bpy.props.StringProperty( 200 | name = "Name",default="group name", 201 | description = "Specify name of edge group") 202 | 203 | 204 | # For the lists in GUI 205 | class block_items(bpy.types.UIList): 206 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): 207 | split = layout.split(0.9) 208 | block = context.active_object.blocks[index] 209 | name = block.name + ' %d'%index 210 | c = split.operator("edit.block", name, emboss=False, icon="UV_FACESEL") 211 | c.blockid = index 212 | c.name = block.name 213 | 214 | if block.enabled: 215 | c = split.operator('enable.block', '',emboss=False,icon="CHECKBOX_HLT").blockid = index 216 | else: 217 | c = split.operator('enable.block','', emboss=False,icon="CHECKBOX_DEHLT").blockid = index 218 | 219 | class boundary_items(bpy.types.UIList): 220 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): 221 | ob = context.active_object 222 | me = data 223 | mat = me.materials[index] 224 | split = layout.split(percentage=0.2) 225 | split.prop(item, "diffuse_color", '') 226 | split.prop(item, "name", '', emboss = False) 227 | split.prop(item, "boundary_type", '', emboss = False) 228 | 229 | class boundaries_action(bpy.types.Operator): 230 | bl_idname = "boundaries.action" 231 | bl_label = "Boundaries action" 232 | 233 | action = bpy.props.EnumProperty( 234 | items=( 235 | ('REMOVE', "Remove", ""), 236 | ('ADD', "Add", ""), 237 | ('ASSIGN', "Assign", ""), 238 | ) 239 | ) 240 | 241 | def invoke(self, context, event): 242 | 243 | ob = context.active_object 244 | bm = bmesh.from_edit_mesh(ob.data) 245 | 246 | if self.action == 'REMOVE': 247 | mat_name = ob.active_material.name 248 | ob.data.materials.pop(ob.active_material_index) 249 | if not bpy.data.materials[mat_name].users: 250 | bpy.data.materials.remove(bpy.data.materials[mat_name]) 251 | 252 | elif self.action == 'ASSIGN': 253 | for f in bm.faces: 254 | if f.select: 255 | f.material_index = ob.boundary_index 256 | ob.data.update() 257 | 258 | if self.action == 'ADD': 259 | name = 'default' 260 | mat = bpy.data.materials.new(name) 261 | color = patchColor(len(ob.data.materials)) 262 | mat.diffuse_color = color 263 | ob.data.materials.append(mat) 264 | material_index = len(ob.data.materials) - 1 265 | 266 | for f in bm.faces: 267 | if f.select: 268 | f.material_index = material_index 269 | ob.boundary_index = material_index 270 | ob.active_material_index = material_index 271 | ob.data.update() 272 | 273 | return {"FINISHED"} 274 | 275 | class projection_items(bpy.types.UIList): 276 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): 277 | split = layout.split(0.4) 278 | proj = context.active_object.projections[index] 279 | if proj.type == 'vert2surf': 280 | icon = "VERTEXSEL" 281 | elif proj.type == 'edge2surf': 282 | icon = "EDGESEL" 283 | elif proj.type == 'face2surf': 284 | icon = "FACESEL" 285 | c = split.operator("get.projection", '{}{}'.format(proj.type[0],proj.id), emboss=False, icon=icon) 286 | c.type = proj.type 287 | c.id = proj.id 288 | split = split.split(0.6) 289 | c = split.operator("activate.object",proj.ob, emboss=False, icon="OBJECT_DATA") 290 | c.ob = proj.ob 291 | c = split.operator('remove.projection','', emboss = False, icon='X') 292 | c.proj_id = index 293 | 294 | # Get all objects in current context 295 | def getProjectionObjects(self, context): 296 | obs = [] 297 | for ob in bpy.data.objects: 298 | if ob.type == "MESH" and not ob.isblockingObject and not ob.ispreviewObject and not ob.isdirectionObject: 299 | obs.append((ob.name, ob.name, '')) 300 | return obs 301 | 302 | # SwiftBlock properties 303 | class BlockProperty(bpy.types.PropertyGroup): 304 | id = bpy.props.IntProperty() 305 | name = bpy.props.StringProperty() 306 | verts = bpy.props.IntVectorProperty(size = 8) 307 | enabled = bpy.props.BoolProperty(default=True) 308 | namedRegion = bpy.props.BoolProperty(default=False) 309 | bpy.utils.register_class(BlockProperty) 310 | 311 | class ProjectionProperty(bpy.types.PropertyGroup): 312 | type = bpy.props.StringProperty() #vert2surf,edge2surf,face2sur,edge2polyline 313 | id = bpy.props.IntProperty() #bmesh id 314 | ob = bpy.props.StringProperty() 315 | bpy.utils.register_class(ProjectionProperty) 316 | 317 | 318 | def updateBoundaryColor(self, context): 319 | ob = context.active_object 320 | mat = bpy.data.materials[self.name] 321 | mat.diffuse_color = self.color 322 | 323 | def updateBoundaryName(self, context): 324 | ob = context.active_object 325 | mat = bpy.data.materials[self.oldName] 326 | mat.name = self.name 327 | self.oldName = mat.name 328 | 329 | class EdgeGroupProperty(bpy.types.PropertyGroup): 330 | group_name = bpy.props.StringProperty() 331 | group_edges = bpy.props.StringProperty() 332 | bpy.utils.register_class(EdgeGroupProperty) 333 | 334 | # Initialize all the bmesh layer properties for the blocking object 335 | class InitBlockingObject(bpy.types.Operator): 336 | bl_idname = "init.blocking" 337 | bl_label = "Init blocking" 338 | bl_options = {"UNDO"} 339 | 340 | def invoke(self, context, event): 341 | print("initialize BMesh") 342 | 343 | bpy.ops.object.mode_set(mode='EDIT') 344 | ob = bpy.context.active_object 345 | bm = bmesh.from_edit_mesh(ob.data) 346 | 347 | bm.edges.layers.string.new("type") 348 | bm.edges.layers.float.new("x1") 349 | bm.edges.layers.float.new("x2") 350 | bm.edges.layers.float.new("r1") 351 | bm.edges.layers.float.new("r2") 352 | bm.edges.layers.float.new("dx") 353 | bm.edges.layers.float.new("ratio") 354 | bm.edges.layers.int.new("cells") 355 | bm.edges.layers.int.new("groupid") 356 | bm.edges.layers.int.new("modtime") 357 | 358 | bm.faces.layers.int.new('pos') # block number on positive side of the face, -1 boundary face 359 | bm.faces.layers.int.new('neg') # block number on negative side of the face, -1 boundary face 360 | bm.faces.layers.int.new('enabled') # 0 = disabled, 1 = boundary face, 2 = internal face 361 | 362 | ob.blocks.clear() 363 | ob.projections.clear() 364 | ob.edge_groups.clear() 365 | bpy.ops.boundaries.action("INVOKE_DEFAULT",action='ADD') 366 | 367 | ob.isblockingObject = True 368 | ob.data.update() 369 | ob.show_all_edges = True 370 | ob.show_wire = True 371 | return {"FINISHED"} 372 | 373 | # Blocking and previewing operators 374 | # Automatical block detection. 375 | class BuildBlocking(bpy.types.Operator): 376 | bl_idname = "build.blocking" 377 | bl_label = "Build blocking" 378 | bl_options = {"UNDO"} 379 | 380 | def invoke(self, context, event): 381 | ob = context.active_object 382 | bm = bmesh.from_edit_mesh(ob.data) 383 | 384 | verts = [] 385 | edges = [] 386 | 387 | for v in bm.verts: 388 | verts.append(v.co) 389 | for e in bm.edges: 390 | edges.append([e.verts[0].index,e.verts[1].index]) 391 | 392 | disabled = [] #not needed anymore 393 | 394 | print('Beginning automatic block detection') 395 | stime = time.time() 396 | log, block_verts, block_edges, face_info, all_edges, faces_as_list_of_nodes = blockBuilder.blockFinder(edges, verts, disabled = disabled, numba = ob.useNumba) 397 | print('Found {} blocks in {:.1f} seconds, used Numba={}'.format(len(block_verts), time.time()-stime,ob.useNumba)) 398 | 399 | 400 | ob.blocks.clear() 401 | for i,bv in enumerate(block_verts): 402 | b = ob.blocks.add() 403 | b.id = i 404 | b.name = 'block'#_{}'.format(i) 405 | b.verts = bv 406 | 407 | groupl = bm.edges.layers.int.get('groupid') 408 | bm.verts.ensure_lookup_table() 409 | 410 | for i, g in enumerate(block_edges): 411 | for e in g: 412 | bme = bm.edges.get((bm.verts[e[0]],bm.verts[e[1]])) 413 | bme[groupl] = i 414 | 415 | # A bug in face_info when there are o-grids. The block indices after o-grid block have to be decreased by one. 416 | replace_ids = dict() 417 | block_ids = [] 418 | for key in face_info.keys(): 419 | block_ids.extend(face_info[key]['pos']) 420 | block_ids.extend(face_info[key]['neg']) 421 | block_ids = sorted(set(block_ids)) 422 | nblocks = len(ob.blocks)-1 423 | 424 | decrease = [] 425 | if nblocks < max(block_ids): 426 | for i in range(max(block_ids)): 427 | if i not in block_ids: 428 | decrease.append(i) 429 | 430 | negl = bm.faces.layers.int.get('neg') 431 | posl = bm.faces.layers.int.get('pos') 432 | enabledl = bm.faces.layers.int.get('enabled') 433 | 434 | block_faces = [] 435 | 436 | for key, value in face_info.items(): 437 | # probably a bug, some extra faces which do not belong to any block 438 | if not value['neg'] and not value['pos']: 439 | continue 440 | verts = [bm.verts[v] for v in faces_as_list_of_nodes[key]] 441 | f = bm.faces.get(verts) 442 | if not f: 443 | f = bm.faces.new(verts) 444 | f[enabledl] = -1 445 | block_faces.append(f) 446 | if value['pos']: 447 | f[posl] = value['pos'][0] 448 | dec = sum(x < f[posl] for x in decrease) 449 | f[posl] -= dec 450 | else: 451 | f[posl] = -1 452 | if value['neg']: 453 | f[negl] = value['neg'][0] 454 | dec = sum(x < f[negl] for x in decrease) 455 | f[negl] -= dec 456 | else: 457 | f[negl] = -1 458 | 459 | for f in bm.faces: 460 | if not f in block_faces: 461 | bm.faces.remove(f) 462 | 463 | 464 | bpy.ops.object.mode_set(mode='OBJECT') 465 | 466 | edgeDirections = utils.getEdgeDirections(block_verts, block_edges) 467 | 468 | ob = bpy.context.active_object 469 | me = ob.data 470 | edgelist = dict() 471 | for e in me.edges: 472 | edgelist[(e.vertices[0],e.vertices[1])] = e.index 473 | for ed in edgeDirections: 474 | # consistentEdgeDirs(ed) 475 | for e in ed: 476 | if (e[0],e[1]) not in edgelist: 477 | ei = me.edges[edgelist[(e[1],e[0])]] 478 | (e0, e1) = ei.vertices 479 | ei.vertices = (e1, e0) 480 | bpy.ops.object.mode_set(mode='EDIT') 481 | updateProjections(ob) 482 | hideFacesEdges(ob, ob.ShowInternalFaces) 483 | bpy.ops.draw.directions('INVOKE_DEFAULT',show=False) 484 | self.report({'INFO'}, "Number of blocks: {}".format(len(block_verts))) 485 | return {"FINISHED"} 486 | 487 | 488 | 489 | 490 | # Build the mesh from already existing blocking 491 | def writeMesh(ob, folder = ''): 492 | if not ob.blocks: 493 | bpy.ops.build.blocking('INVOKE_DEFAULT') 494 | 495 | verts = list(blender_utils.vertices_from_mesh(ob)) 496 | bm = bmesh.from_edit_mesh(ob.data) 497 | 498 | # do not write polylines for hidden edges 499 | edges = [] 500 | for e in bm.edges: 501 | if not e.hide: 502 | edges.append((e.verts[0].index, e.verts[1].index)) 503 | 504 | bpy.ops.object.mode_set(mode='OBJECT') 505 | 506 | 507 | ob.select = False 508 | if ob.Autosnap and ob.EdgeSnapObject: 509 | polyLines, polyLinesPoints, lengths = getPolyLines(verts, edges, ob) 510 | else: 511 | polyLines = [] 512 | lengths = [[]] 513 | verts = [] 514 | matrix = ob.matrix_world.copy() 515 | for v in ob.data.vertices: 516 | verts.append(matrix*v.co) 517 | 518 | blocks = [] 519 | block_names = [] 520 | for b in ob.blocks: 521 | if b.enabled: 522 | blocks.append(list(b.verts)) 523 | if b.namedRegion: 524 | block_names.append(b.name) 525 | else: 526 | block_names.append('') 527 | 528 | edgeInfo = collectEdges(ob,lengths) 529 | 530 | bm = bmesh.from_edit_mesh(ob.data) 531 | detemp = [] 532 | groupl = bm.edges.layers.int.get('groupid') 533 | ngroups = 0 534 | for e in bm.edges: 535 | detemp.append((e[groupl],e.verts[0].index,e.verts[1].index)) 536 | ngroups = max(ngroups,e[groupl]) 537 | 538 | block_edges = [[] for i in range(ngroups+1)] 539 | for e in detemp: 540 | block_edges[e[0]].append([e[1],e[2]]) 541 | 542 | enabledl = bm.faces.layers.int.get('enabled') 543 | bm.verts.ensure_lookup_table() 544 | bm.edges.ensure_lookup_table() 545 | bm.faces.ensure_lookup_table() 546 | 547 | projections = {'vert2surf':dict(),'edge2surf':dict(),'face2surf':dict(), 'geo':dict()} 548 | for p in ob.projections: 549 | if p.type == 'vert2surf' and any([f[enabledl] for f in bm.verts[p.id].link_faces]): 550 | key = bm.verts[p.id].index 551 | if key in projections[p.type]: 552 | projections[p.type][key] += " {}".format(p.ob) 553 | else: 554 | projections[p.type][key] = p.ob 555 | elif p.type == 'edge2surf' and any([f[enabledl] for f in bm.edges[p.id].link_faces]): 556 | key = tuple(v.index for v in bm.edges[p.id].verts) 557 | if key in projections[p.type]: 558 | projections[p.type][key] += " {}".format(p.ob) 559 | else: 560 | projections[p.type][key] = p.ob 561 | elif p.type == 'face2surf' and bm.faces[p.id][enabledl]: 562 | key = tuple(v.index for v in bm.faces[p.id].verts) 563 | projections[p.type][key] = p.ob 564 | 565 | selected_edges = [e.select for e in ob.data.edges] 566 | 567 | boundaries = [{'name':mat.name, 'type':mat.boundary_type, 'faceVerts':[]} for mat in ob.data.materials] 568 | for f in bm.faces: 569 | if f[enabledl] == 1: 570 | boundaries[f.material_index]['faceVerts'].append([v.index for v in f.verts]) 571 | for b in boundaries: 572 | if not b['faceVerts']: 573 | boundaries.remove(b) 574 | 575 | # return edge selection 576 | bpy.ops.mesh.select_all(action='DESELECT') 577 | bpy.ops.object.mode_set(mode='OBJECT') 578 | for e,sel in zip(ob.data.edges,selected_edges): 579 | e.select = sel 580 | 581 | ### This is everything that is related to blockMesh so a new multiblock mesher could be introduced easily just by creating new preview file ### 582 | if ob.Mesher == 'blockMeshMG': 583 | from . import blockMeshMG 584 | importlib.reload(blockMeshMG) 585 | if folder: 586 | mesh = blockMeshMG.PreviewMesh(folder) 587 | else: 588 | mesh = blockMeshMG.PreviewMesh() 589 | # projection_tris = writeProjectionObjects(project_verts,project_edges,project_faces, mesh.geomPath) 590 | if ob.projections: 591 | geos = writeProjectionObjects(ob, mesh.geomPath) 592 | projections['geo'] = geos 593 | 594 | cells = mesh.writeBlockMeshDict(verts, 1, boundaries, polyLines, edgeInfo, block_names, blocks, block_edges, projections) 595 | ############################################################### 596 | elif ob.Mesher == 'blockMeshBodyFit': 597 | from . import blockMeshBodyFit 598 | importlib.reload(blockMeshBodyFit) 599 | if folder: 600 | mesh = blockMeshBodyFit.PreviewMesh(folder) 601 | else: 602 | mesh = blockMeshBodyFit.PreviewMesh() 603 | writeProjectionObjects(ob, mesh.triSurfacePath, onlyFaces = True) 604 | cells = mesh.writeBlockMeshDict(verts, 1, boundaries, polyLines, edgeInfo, block_names, blocks, block_edges, projections, ob.SearchLength) 605 | bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(False,True,False)") 606 | return mesh, cells 607 | 608 | class PreviewMesh(bpy.types.Operator): 609 | bl_idname = "preview.mesh" 610 | bl_label = "Preview mesh" 611 | bl_options = {"UNDO"} 612 | 613 | filename = bpy.props.StringProperty(default='') 614 | 615 | def invoke(self, context, event): 616 | ob = context.active_object 617 | mesh, cells = writeMesh(ob) 618 | points, faces = mesh.runMesh() 619 | blender_utils.previewMesh(ob, points, faces) 620 | self.report({'INFO'}, "Cells in mesh: " + str(cells)) 621 | return {"FINISHED"} 622 | 623 | class WriteMesh(bpy.types.Operator): 624 | bl_idname = "write.mesh" 625 | bl_label = "Write Mesh" 626 | 627 | filepath = bpy.props.StringProperty(subtype='DIR_PATH') 628 | # filepath = bpy.props.StringProperty( 629 | # name="File Path", 630 | # description="Filepath used for exporting the file", 631 | # maxlen=1024, 632 | # subtype='FILE_PATH', 633 | # default='/opt', 634 | # ) 635 | check_existing = bpy.props.BoolProperty( 636 | name="Check Existing", 637 | description="Check and warn on overwriting existing files", 638 | default=True, 639 | options={'HIDDEN'}, 640 | ) 641 | 642 | # use_filter_folder = True 643 | 644 | def invoke(self, context, event): 645 | bpy.context.window_manager.fileselect_add(self) 646 | return {'RUNNING_MODAL'} 647 | 648 | def execute(self, context): 649 | ob = context.active_object 650 | mesh, cells = writeMesh(ob, self.filepath) 651 | bpy.ops.object.mode_set(mode='EDIT') 652 | self.report({'INFO'}, "Cells in mesh: " + str(cells)) 653 | return {"FINISHED"} 654 | 655 | class ActivateBlocking(bpy.types.Operator): 656 | bl_idname = "activate.blocking" 657 | bl_label = "Activate blocking" 658 | bl_options = {"UNDO"} 659 | 660 | hide = bpy.props.BoolProperty() 661 | 662 | def invoke(self, context, event): 663 | scn = context.scene 664 | ob = context.active_object 665 | bob = bpy.data.objects[ob.blocking_object] 666 | blender_utils.activateObject(bob, self.hide) 667 | return {'FINISHED'} 668 | 669 | class GetBlock(bpy.types.Operator): 670 | "Get block from selection" 671 | bl_idname = "get.block" 672 | bl_label = "Get block" 673 | bl_options = {'REGISTER', 'UNDO'} 674 | 675 | def invoke(self, context, event): 676 | ob = bpy.context.active_object 677 | bm = bmesh.from_edit_mesh(ob.data) 678 | selection = [] 679 | for v in bm.verts: 680 | if v.select: 681 | selection.append(v.index) 682 | block = False 683 | occs = [] 684 | for b in ob.blocks: 685 | occ = [v in selection for v in b.verts].count(True) 686 | if occ == 8: 687 | block = b 688 | break 689 | else: 690 | occs.append(occ) 691 | if not block: 692 | max_occ = max(enumerate(occs), key=lambda x:x[1])[0] 693 | block = ob.blocks[max_occ] 694 | if not block: 695 | self.report({'INFO'}, "No block found with selected vertices") 696 | return {'CANCELLED'} 697 | bpy.ops.edit.block('INVOKE_DEFAULT', blockid=block.id, name = block.name ) 698 | return {'FINISHED'} 699 | 700 | class EditBlock(bpy.types.Operator): 701 | bl_idname = "edit.block" 702 | bl_label = "Edit block" 703 | bl_options = {'REGISTER', 'UNDO'} 704 | 705 | 706 | blockid = bpy.props.IntProperty(name='id') 707 | namedRegion = bpy.props.BoolProperty(name='Named region', default = False) 708 | name = bpy.props.StringProperty(name='name') 709 | 710 | def draw(self, context): 711 | ob = context.active_object 712 | if not ob.blocks[self.blockid].enabled: 713 | return 714 | col = self.layout.column(align = True) 715 | # col.prop(self, "enabled") 716 | # split = col.split(percentage=0.1, align=True) 717 | # col = split.column() 718 | col.prop(self, "namedRegion") 719 | if self.namedRegion: 720 | # col = split.column() 721 | col.prop(self, "name") 722 | 723 | # this could be used to select multiple blocks 724 | def invoke(self, context, event): 725 | ob = context.active_object 726 | ob.block_index = self.blockid 727 | if event.shift: 728 | self.shiftDown = True 729 | else: 730 | self.shiftDown = False 731 | self.execute(context) 732 | return {'FINISHED'} 733 | 734 | def execute(self, context): 735 | bpy.ops.mesh.select_all(action="DESELECT") 736 | scn = context.scene 737 | ob = context.active_object 738 | ob.blocks[self.blockid].name = self.name 739 | ob.blocks[self.blockid].namedRegion = self.namedRegion 740 | ob = context.active_object 741 | 742 | verts = ob.blocks[self.blockid].verts 743 | 744 | bm = bmesh.from_edit_mesh(ob.data) 745 | bm.verts.ensure_lookup_table() 746 | for v in verts: 747 | bm.verts[v].select = True 748 | for e in bm.edges: 749 | if e.verts[0].select and e.verts[1].select: 750 | e.select = True 751 | for f in bm.faces: 752 | if len(f.verts) == 4 and sum([v.select for v in f.verts]) == 4: 753 | f.select = True 754 | ob.data.update() 755 | return {'FINISHED'} 756 | 757 | class EnableBlock(bpy.types.Operator): 758 | bl_idname = "enable.block" 759 | bl_label = "Enable/disable block" 760 | 761 | blockid = bpy.props.IntProperty() 762 | 763 | def execute(self, context): 764 | scn = context.scene 765 | ob = context.active_object 766 | block = ob.blocks[self.blockid] 767 | ob.block_index = self.blockid 768 | 769 | if block.enabled: 770 | block.enabled = False 771 | else: 772 | block.enabled = True 773 | # repair_blockFacesEdges(ob) 774 | hideFacesEdges(ob) 775 | 776 | return {'FINISHED'} 777 | 778 | # Mapping operators 779 | 780 | # Change the layer properties of currently selected edges 781 | class SetEdge(bpy.types.Operator): 782 | "Set mapping for the edge" 783 | bl_idname = "set.edgemapping" 784 | bl_label = "Set edge" 785 | bl_options = {"UNDO"} 786 | 787 | def execute(self, context): 788 | ob = context.active_object 789 | scn = context.scene 790 | if not ob.blocks: 791 | bpy.ops.build.blocking('INVOKE_DEFAULT') 792 | 793 | bm = bmesh.from_edit_mesh(ob.data) 794 | typel = bm.edges.layers.string.get('type') 795 | cellsl = bm.edges.layers.int.get('cells') 796 | x1l = bm.edges.layers.float.get('x1') 797 | x2l = bm.edges.layers.float.get('x2') 798 | r1l = bm.edges.layers.float.get('r1') 799 | r2l = bm.edges.layers.float.get('r2') 800 | rl = bm.edges.layers.float.get('ratio') 801 | groupl = bm.edges.layers.int.get('groupid') 802 | timel = bm.edges.layers.int.get('modtime') 803 | 804 | for e in bm.edges: 805 | if e.select: 806 | e[typel] = str.encode(ob.MappingType) 807 | e[cellsl] = ob.Cells 808 | e[timel] = time.time() 809 | if ob.MappingType == "Geometric MG": 810 | e[x1l] = ob.x1 811 | e[x2l] = ob.x2 812 | e[r1l] = ob.r1 813 | e[r2l] = ob.r2 814 | elif ob.MappingType == "Geometric": 815 | e[rl] = ob.Ratio 816 | return {'FINISHED'} 817 | 818 | class GetEdge(bpy.types.Operator): 819 | bl_idname = "get.edge" 820 | bl_label = "Get edge" 821 | bl_options = {"UNDO"} 822 | 823 | def execute(self, context): 824 | ob = context.active_object 825 | scn = context.scene 826 | if not ob.blocks: 827 | bpy.ops.build.blocking('INVOKE_DEFAULT') 828 | 829 | bm = bmesh.from_edit_mesh(ob.data) 830 | typel = bm.edges.layers.string.get('type') 831 | x1l = bm.edges.layers.float.get('x1') 832 | x2l = bm.edges.layers.float.get('x2') 833 | r1l = bm.edges.layers.float.get('r1') 834 | r2l = bm.edges.layers.float.get('r2') 835 | cellsl = bm.edges.layers.int.get('cells') 836 | 837 | for e in bm.edges: 838 | if e.select: 839 | # e[typel] = str.encode(ob.MappingType) 840 | ob.Cells = e[cellsl] 841 | ob.x1 = e[x1l] 842 | ob.x2 = e[x2l] 843 | ob.r1 = e[r1l] 844 | ob.r2 = e[r2l] 845 | return {'FINISHED'} 846 | 847 | class SetCellSize(bpy.types.Operator): 848 | "Calculates the number of cells from maximum cell size" 849 | bl_idname = "set.cellsize" 850 | bl_label = "Set cell size" 851 | bl_options = {"UNDO"} 852 | 853 | def execute(self, context): 854 | ob = context.active_object 855 | scn = context.scene 856 | 857 | bm = bmesh.from_edit_mesh(ob.data) 858 | typel = bm.edges.layers.string.get('type') 859 | x1l = bm.edges.layers.float.get('x1') 860 | x2l = bm.edges.layers.float.get('x2') 861 | r1l = bm.edges.layers.float.get('r1') 862 | r2l = bm.edges.layers.float.get('r2') 863 | cellsl = bm.edges.layers.int.get('cells') 864 | verts = [v.co for v in bm.verts] 865 | edges = [(e.verts[0].index, e.verts[1].index) for e in bm.edges] 866 | 867 | if ob.Autosnap and ob.EdgeSnapObject: 868 | polyLines, polyLinesPoints, lengths = getPolyLines(verts, edges, ob) 869 | else: 870 | polyLines = [] 871 | lengths = [[]] 872 | 873 | 874 | for e in bm.edges: 875 | if e.select: 876 | ev = list([e.verts[0].index,e.verts[1].index]) 877 | if ev in lengths[0]: 878 | ind = lengths[0].index(ev) 879 | L = lengths[1][ind] 880 | else: 881 | L = (e.verts[0].co-e.verts[1].co).length 882 | 883 | e[typel] = str.encode(ob.MappingType) 884 | N=utils.getCells(ob.x1,ob.x2,ob.r1,ob.r2,L,ob.Dx) 885 | e[cellsl] = N 886 | e[x1l] = ob.x1 887 | e[x2l] = ob.x2 888 | e[r1l] = ob.r1 889 | e[r2l] = ob.r2 890 | print(N) 891 | return {'FINISHED'} 892 | 893 | 894 | class EdgeSelectParallel(bpy.types.Operator): 895 | bl_idname = "select.parallel" 896 | bl_label = "Select parallel edges" 897 | 898 | def execute(self, context): 899 | ob = context.active_object 900 | bm = bmesh.from_edit_mesh(ob.data) 901 | groupl = bm.edges.layers.int.get('groupid') 902 | for e in bm.edges: 903 | if e.select: 904 | groupid = e[groupl] 905 | for i in bm.edges: 906 | if i[groupl] == groupid: 907 | i.select = True 908 | ob.data.update() 909 | return {'FINISHED'} 910 | 911 | class FlipEdges(bpy.types.Operator): 912 | "Flips parallel edges, select only one edge per group" 913 | bl_idname = "flip.edges" 914 | bl_label = "Flip edges" 915 | 916 | def execute(self, context): 917 | ob = context.active_object 918 | bm = bmesh.from_edit_mesh(ob.data) 919 | groupl = bm.edges.layers.int.get('groupid') 920 | flip_edges = [] 921 | for e in bm.edges: 922 | if e.select: 923 | groupid = e[groupl] 924 | for i in bm.edges: 925 | if i[groupl] == groupid: 926 | flip_edges.append(i.index) 927 | break 928 | bpy.ops.object.mode_set(mode='OBJECT') 929 | for fe in flip_edges: 930 | e = ob.data.edges[fe] 931 | (e0,e1) = e.vertices 932 | e.vertices = (e1,e0) 933 | bpy.ops.object.mode_set(mode='EDIT') 934 | bpy.ops.draw.directions('INVOKE_DEFAULT',show=False) 935 | return {'FINISHED'} 936 | 937 | def collectEdges(bob, lengths): 938 | bob.select = True 939 | bpy.context.scene.objects.active = bob 940 | bpy.ops.object.mode_set(mode='EDIT') 941 | # snap_vertices = get_snap_vertices(bob) 942 | bm = bmesh.from_edit_mesh(bob.data) 943 | layers = bm.edges.layers 944 | # snapIdl = layers.string.get('snapId') 945 | block_edges = dict() 946 | 947 | timel = layers.int.get('modtime') 948 | groupl = layers.int.get('groupid') 949 | x1l = layers.float.get('x1') 950 | x2l = layers.float.get('x2') 951 | r1l = layers.float.get('r1') 952 | r2l = layers.float.get('r2') 953 | cellsl = layers.int.get('cells') 954 | ratiol = layers.float.get("ratio") 955 | 956 | ncells = dict() 957 | times = dict() 958 | for e in bm.edges: 959 | if e[groupl] not in ncells: 960 | ncells[e[groupl]] = e[cellsl] 961 | times[e[groupl]] = e[timel] 962 | elif e[timel] > times[e[groupl]]: 963 | ncells[e[groupl]] = e[cellsl] 964 | times[e[groupl]] = e[timel] 965 | 966 | for e in bm.edges: 967 | be = dict() 968 | ev = list([e.verts[0].index,e.verts[1].index]) 969 | if ev in lengths[0]: 970 | ind = lengths[0].index(ev) 971 | L = lengths[1][ind] 972 | else: 973 | L = (e.verts[0].co-e.verts[1].co).length 974 | be["type"] = bob.MappingType 975 | be["x1"] = e[x1l] 976 | be["x2"] = e[x2l] 977 | be["r1"] = e[r1l] 978 | be["r2"] = e[r2l] 979 | be["N"] = ncells[e[groupl]] 980 | be["ratio"] = e[ratiol] 981 | be["L"] = L 982 | if not be["N"]: 983 | be["N"] = 10 984 | if not be["r1"]: 985 | be["r1"] = 1. 986 | if not be["r2"]: 987 | be["r2"] = 1. 988 | if not be["ratio"]: 989 | be["ratio"] = 1 990 | be = utils.edgeMapping(be) 991 | block_edges[(e.verts[1].index,e.verts[0].index)] = be 992 | be = dict(be) 993 | be["x1"],be["x2"] = be["x2"],be["x1"] 994 | be["r1"],be["r2"] = be["r2"],be["r1"] 995 | be["ratio"] = 1./be["ratio"] 996 | be = utils.edgeMapping(be) 997 | 998 | block_edges[(e.verts[0].index,e.verts[1].index)] = be 999 | return block_edges 1000 | 1001 | 1002 | # Projection operators 1003 | # TODO Projections are saved to a Blender CollectionProperty. At the 1004 | # moment if verts, edges or faces have been deleted, the id might not be 1005 | # up to date anymore. It would make sense to save the projections to bmesh 1006 | # layer. 1007 | class GetProjection(bpy.types.Operator): 1008 | bl_idname = "get.projection" 1009 | bl_label = "Get projection" 1010 | 1011 | id = bpy.props.IntProperty() 1012 | type = bpy.props.StringProperty() 1013 | 1014 | def invoke(self, context, event): 1015 | if not event.shift: 1016 | bpy.ops.mesh.select_all(action='DESELECT') 1017 | self.execute(context) 1018 | return {'FINISHED'} 1019 | 1020 | 1021 | def execute(self, context): 1022 | ob = context.active_object 1023 | bm = bmesh.from_edit_mesh(ob.data) 1024 | if self.type == 'vert2surf': 1025 | bm.verts.ensure_lookup_table() 1026 | bm.verts[self.id].select = True 1027 | elif self.type == 'edge2surf': 1028 | bm.edges[self.id].select = True 1029 | elif self.type == 'face2surf': 1030 | bm.faces[self.id].select = True 1031 | ob.data.update() 1032 | return {'FINISHED'} 1033 | 1034 | class AddProjections(bpy.types.Operator): 1035 | bl_idname = "add.projections" 1036 | bl_label = "Project to surface" 1037 | bl_options = {"REGISTER","UNDO"} 1038 | 1039 | pob = bpy.props.EnumProperty(name="Projection object", 1040 | items=getProjectionObjects, description = "Projection object") 1041 | 1042 | verts = bpy.props.BoolProperty(default=True) 1043 | edges = bpy.props.BoolProperty(default=True) 1044 | faces = bpy.props.BoolProperty(default=True) 1045 | 1046 | def invoke(self, context, event): 1047 | ob = context.active_object 1048 | self.pob = ob.ProjectionObject 1049 | self.added = 1 1050 | return self.execute(context) 1051 | 1052 | def execute(self, context): 1053 | def projectionExists(ob, ptype, index, pob): 1054 | for p in ob.projections: 1055 | if p.type == ptype and p.id == index and p.ob == pob: 1056 | return True 1057 | return False 1058 | def addProjection(ptype, index): 1059 | for p in ob.projections: 1060 | if p.type == ptype and p.id == index and p.ob == self.pob: 1061 | return 1062 | newp = ob.projections.add() 1063 | newp.type = ptype 1064 | newp.id = index 1065 | newp.ob = self.pob 1066 | self.added += 1 1067 | 1068 | ob = context.active_object 1069 | bm = bmesh.from_edit_mesh(ob.data) 1070 | 1071 | if not self.pob: 1072 | return {"CANCELLED"} 1073 | 1074 | np = len(ob.projections) 1075 | for i in range(self.added): 1076 | ob.projections.remove(np-i) 1077 | 1078 | for v in bm.verts: 1079 | if v.select and self.verts: 1080 | addProjection('vert2surf', v.index) 1081 | 1082 | for e in bm.edges: 1083 | if e.select and self.edges: 1084 | addProjection('edge2surf', e.index) 1085 | 1086 | for f in bm.faces: 1087 | if f.select and self.faces: 1088 | addProjection('face2surf', f.index) 1089 | return {"FINISHED"} 1090 | 1091 | class RemoveProjection(bpy.types.Operator): 1092 | bl_idname = "remove.projection" 1093 | bl_label = "Remove projection" 1094 | bl_options = {"UNDO"} 1095 | 1096 | proj_id = bpy.props.IntProperty(default = -1) 1097 | 1098 | def execute(self, context): 1099 | ob = context.active_object 1100 | if self.proj_id != -1: 1101 | ob.projections.remove(self.proj_id) 1102 | return {"FINISHED"} 1103 | 1104 | class RemoveProjections(bpy.types.Operator): 1105 | bl_idname = "remove.projections" 1106 | bl_label = "Remove projections" 1107 | bl_options = {"UNDO"} 1108 | 1109 | 1110 | def execute(self, context): 1111 | ob = context.active_object 1112 | bm = bmesh.from_edit_mesh(ob.data) 1113 | 1114 | remove_projections = [] 1115 | 1116 | for v in bm.verts: 1117 | if v.select: 1118 | for i,p in enumerate(ob.projections): 1119 | if p.type == 'vert2surf' and p.id == v.index: 1120 | remove_projections.append(i) 1121 | for e in bm.edges: 1122 | if e.select: 1123 | for i,p in enumerate(ob.projections): 1124 | if p.type == 'edge2surf' and p.id == e.index: 1125 | remove_projections.append(i) 1126 | for f in bm.faces: 1127 | if f.select: 1128 | for i,p in enumerate(ob.projections): 1129 | if p.type == 'face2surf' and p.id == f.index: 1130 | remove_projections.append(i) 1131 | remove_projections = reversed(sorted(remove_projections)) 1132 | for i in remove_projections: 1133 | ob.projections.remove(i) 1134 | return {"FINISHED"} 1135 | 1136 | def writeProjectionObjects(ob, path, onlyFaces = False): 1137 | blender_version = bpy.app.version[1] 1138 | objects = [] 1139 | for p in ob.projections: 1140 | if onlyFaces and not p.type == 'face2surf': 1141 | continue 1142 | else: 1143 | objects.append(p.ob) 1144 | objects = set(objects) 1145 | for o in objects: 1146 | sob = bpy.data.objects[o] 1147 | hide = sob.hide 1148 | blender_utils.activateObject(sob) 1149 | # In older Blender versions < 2.76 only the selection is exported. 1150 | # In newer versions there is a new argument use_selection which is by default False. 1151 | if blender_version < 77: 1152 | bpy.ops.export_mesh.stl('EXEC_DEFAULT',filepath = path + '/{}.stl'.format(o)) 1153 | else: 1154 | bpy.ops.export_mesh.stl('EXEC_DEFAULT',filepath = path + '/{}.stl'.format(o),use_selection=True) 1155 | sob.hide = hide 1156 | blender_utils.activateObject(ob) 1157 | return objects 1158 | 1159 | class ActivateSnap(bpy.types.Operator): 1160 | bl_idname = "activate.object" 1161 | bl_label = "Activate snapping object" 1162 | bl_options = {"UNDO"} 1163 | 1164 | ob = bpy.props.StringProperty() 1165 | 1166 | 1167 | def invoke(self, context, event): 1168 | scn = context.scene 1169 | ob = context.active_object 1170 | pob = bpy.data.objects[self.ob] 1171 | pob.blocking_object = ob.name 1172 | blender_utils.activateObject(pob, False) 1173 | return {'FINISHED'} 1174 | 1175 | class EdgetoPolyLine(bpy.types.Operator): 1176 | bl_idname = "edge.topolyline" 1177 | bl_label = "Project edge to polyline" 1178 | bl_options = {"REGISTER", "UNDO"} 1179 | 1180 | def invoke(self, context, event): 1181 | scn = context.scene 1182 | self.ob = context.active_object 1183 | bm = bmesh.from_edit_mesh(self.ob.data) 1184 | 1185 | for e in bm.edges: 1186 | if e.select: 1187 | self.edge = e.index 1188 | 1189 | self.proj_ob = bpy.data.objects[self.ob.ProjectionObject] 1190 | blender_utils.activateObject(self.proj_ob) 1191 | context.window_manager.modal_handler_add(self) 1192 | 1193 | return {'RUNNING_MODAL'} 1194 | 1195 | def modal(self, context, event): 1196 | if event.type in {'RIGHTMOUSE', 'RETURN'}: 1197 | bm = bmesh.from_edit_mesh(self.proj_ob.data) 1198 | selected_edges = [] 1199 | projl = bm.edges.layers.string.get("projectionEdgeId") 1200 | if not projl: 1201 | projl = bm.edges.layers.int.new("projectionEdgeId") 1202 | self.proj_ob.data.update() 1203 | for e in bm.edges: 1204 | if e.select: 1205 | e[projl] = self.edge 1206 | blender_utils.activateObject(self.ob) 1207 | return {'FINISHED'} 1208 | elif event.type in 'ESC': 1209 | return {'CANCELLED'} 1210 | else: 1211 | return {'PASS_THROUGH'} 1212 | 1213 | 1214 | # This function checks that the vert, edge or face is still there. 1215 | # Unfortunately, the projection ids might be wrong if verts, edges 1216 | # or faces have been deleted. 1217 | def updateProjections(ob): 1218 | bm = bmesh.from_edit_mesh(ob.data) 1219 | bm.verts.ensure_lookup_table() 1220 | bm.edges.ensure_lookup_table() 1221 | bm.faces.ensure_lookup_table() 1222 | remove_projections = [] 1223 | for i, p in enumerate(ob.projections): 1224 | try: 1225 | if p.type == 'vert2surf': 1226 | bm.verts[p.id] 1227 | elif p.type == 'edge2surf': 1228 | bm.edges[p.id] 1229 | elif p.type == 'face2surf': 1230 | bm.faces[p.id] 1231 | except IndexError: 1232 | remove_projections.append(i) 1233 | for pid in reversed(sorted(remove_projections)): 1234 | ob.projections.remove(pid) 1235 | 1236 | # Boundary condition operators 1237 | def selectActiveBoundary(self, context): 1238 | ob = context.active_object 1239 | ob.active_material_index = ob.boundary_index 1240 | 1241 | bm = bmesh.from_edit_mesh(ob.data) 1242 | bpy.ops.mesh.select_all(action='DESELECT') 1243 | 1244 | for f in bm.faces: 1245 | if f.material_index == ob.boundary_index: 1246 | f.select = True 1247 | 1248 | 1249 | def patchColor(patch_no): 1250 | color = [(0.25,0.25,0.25), (1.0,0.,0.), (0.0,1.,0.),(0.0,0.,1.),(0.707,0.707,0),(0,0.707,0.707),(0.707,0,0.707)] 1251 | return color[patch_no % len(color)] 1252 | 1253 | 1254 | 1255 | # Edge group operators 1256 | class RemoveEdgeGroup(bpy.types.Operator): 1257 | bl_idname = "remove.edgegroup" 1258 | bl_label = "Remove edge group" 1259 | egName = bpy.props.StringProperty() 1260 | 1261 | def execute(self, context): 1262 | scn = context.scene 1263 | ob = context.active_object 1264 | for i,eg in enumerate(ob.edge_groups): 1265 | if eg.group_name == self.egName: 1266 | ob.edge_groups.remove(i) 1267 | return {'FINISHED'} 1268 | return {'CANCEL'} 1269 | 1270 | class GetEdgeGroup(bpy.types.Operator): 1271 | bl_idname = "get.edgegroup" 1272 | bl_label = "Get edge group" 1273 | 1274 | egName = bpy.props.StringProperty() 1275 | 1276 | def execute(self, context): 1277 | scn = context.scene 1278 | ob = context.active_object 1279 | bpy.ops.mesh.select_all(action="DESELECT") 1280 | 1281 | bm = bmesh.from_edit_mesh(ob.data) 1282 | for eg in ob.edge_groups: 1283 | if eg.group_name == self.egName: 1284 | edges = list(map(int,eg.group_edges.split(','))) 1285 | for e in edges: 1286 | bm.edges[e].select = True 1287 | ob.data.update() 1288 | return {'FINISHED'} 1289 | 1290 | 1291 | class AddEdgeGroup(bpy.types.Operator): 1292 | '''Set the given name to the selected edges''' 1293 | bl_idname = "add.edgegroup" 1294 | bl_label = "Add edge group" 1295 | 1296 | def execute(self, context): 1297 | scn = context.scene 1298 | ob = context.active_object 1299 | ob.data.update() 1300 | edges = [] 1301 | for e in ob.data.edges: 1302 | if e.select: 1303 | edges.append(e.index) 1304 | edgesstr = ','.join(map(str,edges)) 1305 | for e in ob.edge_groups: 1306 | if e.group_name == ob.EdgeGroupName: 1307 | e.group_edges = edgesstr 1308 | return {'FINISHED'} 1309 | eg = ob.edge_groups.add() 1310 | eg.group_name = ob.EdgeGroupName 1311 | eg.group_edges = edgesstr 1312 | return {'FINISHED'} 1313 | 1314 | # Other stuff 1315 | class BlockExtrusion(bpy.types.Operator): 1316 | "Extrude blocks without removing internal edges" 1317 | bl_idname = "extrude.blocks" 1318 | bl_label = "Extrude blocks" 1319 | bl_options = {'REGISTER', 'UNDO'} 1320 | 1321 | def execute(self, context): 1322 | ob = bpy.context.active_object 1323 | bm = bmesh.from_edit_mesh(ob.data) 1324 | sel_mode = bpy.context.scene.tool_settings.mesh_select_mode 1325 | bpy.context.scene.tool_settings.mesh_select_mode = (False, True, False) 1326 | selected_faces = [] 1327 | for f in bm.faces: 1328 | if f.select: 1329 | selected_faces.append((f,[v for v in f.verts])) 1330 | bpy.ops.mesh.extrude_faces_move() 1331 | for f in selected_faces: 1332 | newf = bm.faces.new(f[1]) 1333 | for p in ob.projections: 1334 | if p.type == 'face' and p.id == f[0].index: 1335 | p.id = newf.index 1336 | bpy.ops.mesh.remove_doubles(threshold=0.0001, use_unselected=False) 1337 | ob.data.update() 1338 | bpy.ops.transform.translate('INVOKE_REGION_WIN') 1339 | return {"FINISHED"} 1340 | 1341 | def blockExtrusion_menu(self, context): 1342 | self.layout.operator("extrude.blocks") 1343 | 1344 | def changeMesher(self, context): 1345 | ob = context.active_object 1346 | if ob.Mesher == "blockMeshMG": 1347 | ob.MappingType = "Geometric MG" 1348 | elif ob.Mesher == "blockMeshBodyFit": 1349 | ob.MappingType = "Geometric" 1350 | 1351 | class DrawEdgeDirections(bpy.types.Operator): 1352 | "Draw edge directions" 1353 | bl_idname = "draw.directions" 1354 | bl_label = "draw edge directions" 1355 | bl_options = {'REGISTER', 'UNDO'} 1356 | 1357 | show = bpy.props.BoolProperty(default=True) 1358 | size = bpy.props.FloatProperty(default=0,min=0) 1359 | verts = bpy.props.IntProperty(default=12,min=0) 1360 | relativeSize = bpy.props.BoolProperty(default=True) 1361 | 1362 | def invoke(self, context, event): 1363 | self.bob = bpy.context.active_object 1364 | bm = bmesh.from_edit_mesh(self.bob.data) 1365 | self.edges = [] 1366 | for e in bm.edges: 1367 | if not e.hide: 1368 | self.edges.append((Vector(e.verts[0].co[:]),Vector(e.verts[1].co[:]))) 1369 | self.lengths = [(e[0]-e[1]).length for e in self.edges] 1370 | self.size = 0.1 1371 | self.execute(context) 1372 | return {"FINISHED"} 1373 | 1374 | 1375 | def execute(self,context): 1376 | try: 1377 | eob = bpy.data.objects['Edge_directions'] 1378 | self.remove(context,eob) 1379 | except: 1380 | pass 1381 | if not self.edges or not self.show: 1382 | self.bob.direction_object = '' 1383 | return {"CANCELLED"} 1384 | bpy.ops.object.mode_set(mode='OBJECT') 1385 | bpy.ops.mesh.primitive_cone_add(vertices=self.verts,radius1=0.3,depth=1)#,end_fill_type='NOTHING') 1386 | default_arrow = context.active_object 1387 | arrows = [] 1388 | # this is "a bit" slow 1389 | for e,l in zip(self.edges,self.lengths): 1390 | v1 = Vector(e[0]) 1391 | v2 = Vector(e[1]) 1392 | tob = bpy.data.objects.new("Arrow_duplicate", default_arrow.data) 1393 | tob.location = v1+0.5*(v2-v1) 1394 | if self.relativeSize: 1395 | scale = self.size*l 1396 | else: 1397 | scale = self.size 1398 | tob.scale = (scale,scale,scale) 1399 | tob.rotation_mode = 'QUATERNION' 1400 | tob.rotation_quaternion = (v1-v2).to_track_quat('Z','Y') 1401 | context.scene.objects.link(tob) 1402 | arrows.append(tob) 1403 | tob.select = True 1404 | aob = arrows[0] 1405 | bpy.context.scene.objects.active = aob 1406 | aob.name = 'Edge_directions' 1407 | aob.hide_select = True 1408 | 1409 | mat = bpy.data.materials.new('black') 1410 | mat.emit = 2 1411 | mat.diffuse_color = (0,0,0) 1412 | bpy.ops.object.material_slot_add() 1413 | aob.material_slots[-1].material = mat 1414 | self.remove(context, default_arrow) 1415 | aob.isdirectionObject = True 1416 | 1417 | bpy.ops.object.join() 1418 | bpy.ops.object.shade_smooth() 1419 | blender_utils.activateObject(self.bob) 1420 | self.bob.direction_object = aob.name 1421 | return {"FINISHED"} 1422 | 1423 | def remove(self, context, ob): 1424 | context.scene.objects.unlink(ob) 1425 | bpy.data.objects.remove(ob) 1426 | 1427 | def showInternalFaces(self, context): 1428 | ob = context.active_object 1429 | hideFacesEdges(ob, ob.ShowInternalFaces) 1430 | 1431 | def hideFacesEdges(ob, showInternal = False): 1432 | ob.data.update() 1433 | bm = bmesh.from_edit_mesh(ob.data) 1434 | bm.verts.ensure_lookup_table() 1435 | 1436 | negl = bm.faces.layers.int.get('neg') 1437 | posl = bm.faces.layers.int.get('pos') 1438 | enabledl = bm.faces.layers.int.get('enabled') 1439 | 1440 | for f in bm.faces: 1441 | if f[negl] != -1 and f[posl] != -1: 1442 | if (not ob.blocks[f[posl]].enabled and ob.blocks[f[negl]].enabled) \ 1443 | or (ob.blocks[f[posl]].enabled and not ob.blocks[f[negl]].enabled): 1444 | # boundary face 1445 | f.hide_set(False)# = False 1446 | f[enabledl] = 1 1447 | elif not ob.blocks[f[posl]].enabled and not ob.blocks[f[negl]].enabled: 1448 | # both blocks disabled 1449 | f[enabledl] = False 1450 | f.hide = True 1451 | elif showInternal: 1452 | # internal face 1453 | f[enabledl] = 2 1454 | f.hide_set(False) 1455 | else: 1456 | # internal face 1457 | f[enabledl] = 2 1458 | f.hide = True 1459 | elif (f[posl] == -1 and f[negl] != -1): #boundary face 1460 | if ob.blocks[f[negl]].enabled: 1461 | # boundary face 1462 | f.hide_set(False)# = False 1463 | f[enabledl] = 1 1464 | else: 1465 | # boundary block disabled 1466 | f.hide_set(True) 1467 | f[enabledl] = False 1468 | elif (f[posl] != -1 and f[negl] == -1): #boundary face 1469 | if ob.blocks[f[posl]].enabled: 1470 | # boundary face 1471 | f.hide_set(False) 1472 | f[enabledl] = 1 1473 | else: 1474 | # boundary block disabled 1475 | f.hide_set(True) 1476 | f[enabledl] = False 1477 | 1478 | for e in bm.edges: 1479 | edge_found = False 1480 | for b in ob.blocks: 1481 | if b.enabled and e.verts[0].index in b.verts and e.verts[1].index in b.verts: 1482 | edge_found = True 1483 | e.hide = False 1484 | continue 1485 | if not edge_found: 1486 | e.hide_set(True) 1487 | 1488 | bpy.ops.draw.directions('INVOKE_DEFAULT',show=False) 1489 | ob.data.update() 1490 | 1491 | 1492 | 1493 | # Kalle's implementation 1494 | def getPolyLines(verts, edges, bob): 1495 | scn = bpy.context.scene 1496 | polyLinesPoints = [] 1497 | polyLines = '' 1498 | polyLinesLengths = [[], []] 1499 | tol = 1e-6 1500 | 1501 | def isPointOnEdge(point, A, B): 1502 | eps = (((A - B).magnitude - (point-B).magnitude) - (A-point).magnitude) 1503 | return True if (abs(eps) < tol) else False 1504 | 1505 | # nosnap= [False for i in range(len(edges))] 1506 | # for eid, e in enumerate(obj.data.edges): 1507 | # nosnap[eid] = e.use_edge_sharp 1508 | 1509 | bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)") 1510 | geoobj = bpy.data.objects[bob.EdgeSnapObject] 1511 | geo_verts = list(blender_utils.vertices_from_mesh(geoobj)) 1512 | geo_edges = list(blender_utils.edges_from_mesh(geoobj)) 1513 | geoobj.select = False # avoid deletion 1514 | 1515 | # First go through all vertices in the block structure and find vertices snapped to edges 1516 | # When found, add a vertex at that location to the polyLine object by splitting the edge 1517 | # Create a new Blender object containing the newly inserted verts. Then use Blender's 1518 | # shortest path algo to find polyLines. 1519 | 1520 | for vid, v in enumerate(verts): 1521 | found = False 1522 | for gvid, gv in enumerate(geo_verts): 1523 | mag = (v-gv).magnitude 1524 | if mag < tol: 1525 | found = True 1526 | break # We have found a vertex co-located, continue with next block vertex 1527 | if not found: 1528 | for geid, ge in enumerate(geo_edges): 1529 | if (isPointOnEdge(v, geo_verts[ge[0]], geo_verts[ge[1]])): 1530 | geo_verts.append(v) 1531 | geo_edges.append([geo_edges[geid][1],len(geo_verts)-1]) # Putting the vert on the edge, by splitting it in two. 1532 | geo_edges[geid][1] = len(geo_verts)-1 1533 | break # No more iteration, go to next block vertex 1534 | 1535 | mesh_data = bpy.data.meshes.new("deleteme") 1536 | mesh_data.from_pydata(geo_verts, geo_edges, []) 1537 | mesh_data.update() 1538 | geoobj = bpy.data.objects.new('deleteme', mesh_data) 1539 | bpy.context.scene.objects.link(geoobj) 1540 | geo_verts = list(blender_utils.vertices_from_mesh(geoobj)) 1541 | geo_edges = list(blender_utils.edges_from_mesh(geoobj)) 1542 | bpy.context.scene.objects.active=geoobj 1543 | 1544 | # Now start the search over again on the new object with more verts 1545 | snapped_verts = {} 1546 | for vid, v in enumerate(verts): 1547 | for gvid, gv in enumerate(geo_verts): 1548 | mag = (v-gv).magnitude 1549 | if mag < tol: 1550 | snapped_verts[vid] = gvid 1551 | break # We have found a vertex co-located, continue with next block vertex 1552 | 1553 | bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(True,False,False)") 1554 | for edid, ed in enumerate(edges): 1555 | if ed[0] in snapped_verts and ed[1] in snapped_verts:# and not nosnap[edid]: 1556 | geoobj.hide = False 1557 | bpy.ops.object.mode_set(mode='EDIT') 1558 | bpy.ops.mesh.select_all(action='DESELECT') 1559 | bpy.ops.object.mode_set(mode='OBJECT') 1560 | geoobj.data.vertices[snapped_verts[ed[0]]].select = True 1561 | geoobj.data.vertices[snapped_verts[ed[1]]].select = True 1562 | bpy.ops.object.mode_set(mode='EDIT') 1563 | try: 1564 | bpy.ops.mesh.select_vertex_path(type='EDGE_LENGTH') 1565 | except: 1566 | bpy.ops.mesh.shortest_path_select() 1567 | bpy.ops.object.mode_set(mode='OBJECT') 1568 | bpy.ops.object.mode_set(mode='EDIT') 1569 | bpy.ops.mesh.duplicate() 1570 | bpy.ops.object.mode_set(mode='OBJECT') 1571 | bpy.ops.object.mode_set(mode='EDIT') 1572 | bpy.ops.mesh.separate(type='SELECTED') 1573 | bpy.ops.object.mode_set(mode='OBJECT') 1574 | polyLineobj = bpy.data.objects['deleteme.001'] 1575 | if len(polyLineobj.data.vertices) > 2: 1576 | polyLineverts = list(blender_utils.vertices_from_mesh(polyLineobj)) 1577 | polyLineedges = list(blender_utils.edges_from_mesh(polyLineobj)) 1578 | for vid, v in enumerate(polyLineverts): 1579 | mag = (v-verts[ed[0]]).magnitude 1580 | if mag < tol: 1581 | startVertex = vid 1582 | break 1583 | polyLineStr, vectors, length = sortedVertices(polyLineverts,polyLineedges,startVertex) 1584 | polyLinesPoints.append([ed[0],ed[1],vectors]) 1585 | polyLinesLengths[0].append([min(ed[0],ed[1]), max(ed[0],ed[1])]) # write out sorted 1586 | polyLinesLengths[1].append(length) 1587 | polyLine = 'polyLine {} {} ('.format(*ed) 1588 | polyLine += polyLineStr 1589 | polyLine += ')\n' 1590 | polyLines += polyLine 1591 | 1592 | geoobj.select = False 1593 | polyLineobj.select = True 1594 | bpy.ops.object.delete() 1595 | geoobj.select = True 1596 | bpy.ops.object.delete() 1597 | return polyLines, polyLinesPoints, polyLinesLengths 1598 | 1599 | def sortedVertices(verts,edges,startVert): 1600 | sorted = [] 1601 | vectors = [] 1602 | sorted.append(startVert) 1603 | vert = startVert 1604 | length = len(edges)+1 1605 | for i in range(len(verts)): 1606 | for eid, e in enumerate(edges): 1607 | if vert in e: 1608 | if e[0] == vert: 1609 | sorted.append(e[1]) 1610 | else: 1611 | sorted.append(e[0]) 1612 | edges.pop(eid) 1613 | vert = sorted[-1] 1614 | break 1615 | 1616 | polyLine = '' 1617 | length = 0. 1618 | for vid, v in enumerate(sorted): 1619 | polyLine += '({} {} {})'.format(*verts[v]) 1620 | vectors.append(verts[v]) 1621 | if vid>=1: 1622 | length += (vectors[vid] - vectors[vid-1]).magnitude 1623 | return polyLine, vectors, length 1624 | 1625 | initSwiftBlockProperties() 1626 | 1627 | def register(): 1628 | bpy.utils.register_module(__name__) 1629 | bpy.types.VIEW3D_MT_edit_mesh_extrude.prepend(blockExtrusion_menu) 1630 | def unregister(): 1631 | bpy.utils.unregister_module(__name__) 1632 | bpy.types.VIEW3D_MT_edit_mesh_extrude.remove(blockExtrusion_menu) 1633 | if __name__ == "__main__": 1634 | register() 1635 | -------------------------------------------------------------------------------- /blender_utils.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from mathutils import Vector, Matrix, Euler 21 | import bgl 22 | import bmesh 23 | 24 | 25 | 26 | def vertices_from_mesh(ob): 27 | ''' 28 | ''' 29 | 30 | # get the modifiers 31 | try: 32 | mesh = ob.to_mesh(bpy.context.scene, False, "PREVIEW") 33 | except RuntimeError: 34 | raise StopIteration 35 | 36 | matrix = ob.matrix_world.copy() 37 | 38 | for v in mesh.vertices: 39 | yield (matrix*v.co) 40 | 41 | bpy.data.meshes.remove(mesh) 42 | 43 | def edges_from_mesh(ob): 44 | ''' 45 | ''' 46 | 47 | # get the modifiers 48 | try: 49 | mesh = ob.to_mesh(bpy.context.scene, False, "PREVIEW") 50 | except RuntimeError: 51 | raise StopIteration 52 | 53 | for e in mesh.edges: 54 | yield list(e.vertices) 55 | 56 | bpy.data.meshes.remove(mesh) 57 | 58 | def activateObject(ob, hideCurrent = False): 59 | context = bpy.context 60 | bpy.ops.object.mode_set(mode='OBJECT') 61 | cob = context.active_object 62 | if cob: 63 | cob.hide = hideCurrent 64 | cob.select = False 65 | scn = context.scene 66 | ob.select = True 67 | ob.hide = False 68 | bpy.context.scene.objects.active = ob 69 | bpy.ops.object.mode_set(mode='EDIT') 70 | 71 | 72 | def previewMesh(ob, points, faces): 73 | blocking = ob 74 | blocking.hide = True 75 | blocking.select = False 76 | scn = bpy.context.scene 77 | if not ob.preview_object or not ob.preview_object in bpy.data.objects: 78 | mesh_data = bpy.data.meshes.new("previewMesh") 79 | previewMeshOb = bpy.data.objects.new('previewMesh', mesh_data) 80 | previewMeshOb.ispreviewObject = True 81 | scn.objects.link(previewMeshOb) 82 | ob.preview_object = previewMeshOb.name 83 | else: 84 | previewMeshOb = bpy.data.objects["previewMesh"] 85 | oldme = previewMeshOb.data 86 | mesh_data = bpy.data.meshes.new("previewMesh") 87 | previewMeshOb.data = mesh_data 88 | bpy.data.meshes.remove(oldme) 89 | previewMeshOb.hide = False 90 | previewMeshOb.select = True 91 | previewMeshOb.blocking_object = blocking.name 92 | mesh_data.from_pydata(points, [], faces) 93 | mesh_data.update() 94 | 95 | scn.objects.active = previewMeshOb 96 | bpy.context.object.data.show_extra_edge_length = True 97 | bpy.ops.object.mode_set(mode='EDIT') 98 | bpy.ops.object.mode_set(mode='EDIT') 99 | bpy.ops.mesh.select_all(action='DESELECT') 100 | bpy.ops.object.mode_set(mode='OBJECT') 101 | previewMeshOb.show_all_edges = True 102 | previewMeshOb.show_wire = True 103 | 104 | arrow_head = [ 105 | [-1,-1], 106 | [0,0], 107 | [1,-1], 108 | ] 109 | def draw_arrow_head(ob, vecFrom, vecTo): 110 | if ob is None: 111 | return 112 | 113 | direction = Vector(vecTo) - Vector(vecFrom) 114 | print(direction) 115 | # direction.resize_2d() 116 | # print(direction) 117 | angle = direction.angle(Vector((0,1,0))) 118 | 119 | # form a 2d rotation matrix 120 | mat = Matrix().Rotation(angle, 2) 121 | 122 | # middle point 123 | middle = (Vector(vecTo) + Vector(vecFrom)) / 2.0 124 | 125 | 126 | bgl.glEnable(bgl.GL_BLEND) 127 | bgl.glBegin(bgl.GL_LINE_STRIP) 128 | for v in arrow_head: 129 | xy = Vector(v)* 1.0 * mat 130 | xy.resize_3d() 131 | newPos = xy + middle 132 | bgl.glVertex3f(*newPos) 133 | bgl.glLineWidth(2) 134 | bgl.glColor4f(0.0,0.0,0.0,0.5) 135 | bgl.glEnd() 136 | 137 | # bgl.glEnable(bgl.GL_BLEND) 138 | # bgl.glBegin(bgl.GL_LINES) 139 | # bgl.glVertex3f(*(middle-Vector((1,0,0)))) 140 | # bgl.glVertex3f(*(middle-Vector((-1,0,0)))) 141 | # bgl.glVertex3f(*(middle-Vector((0,1,0)))) 142 | # bgl.glVertex3f(*(middle-Vector((0,-1,0)))) 143 | # print((middle-Vector((1,0,0))),(middle-Vector((-1,0,0)))) 144 | 145 | def draw_edge_direction(self,context): 146 | ob = bpy.context.active_object 147 | if ob is None: 148 | return 149 | if bpy.context.active_object.mode != 'EDIT': 150 | return 151 | me = ob.data 152 | bm = bmesh.from_edit_mesh(me) 153 | # draw_arrow_head(bm.edges[0]) 154 | bgl.glEnable(bgl.GL_BLEND) 155 | for e in bm.edges: 156 | draw_arrow_head(ob, e.verts[0].co, e.verts[1].co) 157 | bgl.glEnd() 158 | bgl.glLineWidth(1) 159 | bgl.glDisable(bgl.GL_BLEND) 160 | bgl.glColor4f(0.0,0.0,0.0,1.0) 161 | 162 | class EdgeVisualiser(bpy.types.Operator): 163 | bl_idname = "edge.visualiser" 164 | bl_label = "Edge Visualiser" 165 | bl_description = "Show edge directions" 166 | 167 | def modal(self, context, event): 168 | context.area.tag_redraw() 169 | if event.type == 'ESC': 170 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 171 | return {"CANCELLED"} 172 | return {"PASS_THROUGH"} 173 | 174 | def invoke(self, context, event): 175 | args = (self, context) 176 | if context.area.type == "VIEW_3D": 177 | self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_edge_direction, args, 'WINDOW', 'POST_VIEW') 178 | context.window_manager.modal_handler_add(self) 179 | return {"RUNNING_MODAL"} 180 | else: 181 | self.report({"WARNING"}, "View3D not found, can't run operator") 182 | return {"CANCELLED"} 183 | -------------------------------------------------------------------------------- /blockBuilder.py: -------------------------------------------------------------------------------- 1 | import mathutils 2 | import time 3 | import importlib 4 | import numpy as np 5 | # from . import cycleFinderNumba 6 | # importlib.reload(cycleFinderNumba) 7 | 8 | def removedup(seq): 9 | checked = [] 10 | for e in seq: 11 | if e not in checked: 12 | checked.append(e) 13 | return checked 14 | 15 | def edge(e0, e1): 16 | return [min(e0,e1), max(e0,e1)] 17 | 18 | def couple_edges(dependent_edges): 19 | for es0, edgeSet0 in enumerate(dependent_edges): 20 | for edge in edgeSet0: 21 | for es1, edgeSet1 in enumerate(dependent_edges): 22 | if edge in edgeSet1 and es0 != es1: 23 | for e in edgeSet0: 24 | edgeSet1.append(e) 25 | dependent_edges.pop(es0) 26 | return True 27 | return False 28 | 29 | 30 | 31 | def findFace(faces, vl): 32 | for fid, f in enumerate(faces): 33 | if vl[0] in f and vl[1] in f and vl[2] in f and vl[3] in f: 34 | return fid, f 35 | return -1, [] 36 | 37 | 38 | def cycleFinder(edges,verts): 39 | # Credit: Adam Gaither. An Efficient Block Detection Algorithm For Structured Grid Generation 40 | verticesId = verts 41 | edgeVisited = np.zeros(len(edges), dtype=bool) 42 | faces = [] 43 | facesEdges = [] 44 | no_edges = 0 45 | 46 | v_in_edge = [[] for i in range(len(verts))] 47 | for v in verts: 48 | for eid, e in enumerate(edges): 49 | if v in e: 50 | v_in_edge[v].append(eid) 51 | v_in_edges = np.array(v_in_edge) 52 | 53 | for v in verticesId: 54 | currentCycle = [v] 55 | currentCycleEdges = [] 56 | buildFourEdgeFaces(v, v_in_edge, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges) 57 | 58 | faces = np.reshape(faces,(-1,4)) 59 | temp, u = np.unique(np.sort(faces), axis=0, return_index=True) 60 | faces = faces[u] 61 | facesP = [list(map(np.asscalar,f)) for f in faces] 62 | 63 | facesEdges = np.reshape(facesEdges,(-1,4)) 64 | facesEdges = facesEdges[u] 65 | facesEdgesP = [list(map(np.asscalar,f)) for f in facesEdges] 66 | 67 | return facesP, facesEdgesP 68 | 69 | def buildFourEdgeFaces(v, v_in_edge, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges): 70 | for eid in v_in_edge[v]: 71 | if not edgeVisited[eid]: 72 | e = edges[eid] 73 | no_edges += 1 74 | edgeVisited[eid] = True 75 | opposite_v = e[0] 76 | if opposite_v == v: # seems the other vertex is in e[1]! 77 | opposite_v = e[1] 78 | currentCycle.append(opposite_v) 79 | currentCycleEdges.append(eid) 80 | if currentCycle[0] == currentCycle[-1]: # First equals last -> we have a face 81 | if len(currentCycle) == 5: 82 | faces.extend(currentCycle[0:4]) 83 | if len(currentCycleEdges) == 4: 84 | facesEdges.extend(currentCycleEdges[0:4]) 85 | else: 86 | if no_edges < 4: 87 | buildFourEdgeFaces(opposite_v, v_in_edge, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges) 88 | no_edges -= 1 89 | currentCycle.pop() 90 | currentCycleEdges.pop() 91 | edgeVisited[eid] = False 92 | 93 | 94 | def blockFinder(edges, vertices_coord, logFileName='', debugFileName='', disabled = [], numba=False): 95 | if len(logFileName) > 0: 96 | logFile = open(logFileName,'w') 97 | else: 98 | logFile = '' 99 | 100 | # Use the cycle finder class to find all edges forming quad faces 101 | if numba: 102 | from . import cycleFinderNumba 103 | tmp_v,tmp_e = cycleFinderNumba.cycleFinder(edges,range(len(vertices_coord))) 104 | else: 105 | tmp_v,tmp_e = cycleFinder(edges,range(len(vertices_coord))) 106 | 107 | faces_as_list_of_vertices = [] 108 | faces_as_list_of_nodes = [] 109 | faces_as_list_of_edges = [] 110 | for ii, i in enumerate(tmp_v): # get rid of possible triangles 111 | if len(i) == 4: 112 | faces_as_list_of_vertices.append([vertices_coord[i[0]], vertices_coord[i[1]], vertices_coord[i[2]], vertices_coord[i[3]]]) 113 | faces_as_list_of_nodes.append(i) 114 | faces_as_list_of_edges.append(tmp_e[ii]) 115 | # Create a wavefront obj file showing all the faces just found 116 | if len(debugFileName) > 0: 117 | debugFile = open(debugFileName,'w') 118 | for v in vertices_coord: 119 | debugFile.write('v {} {} {}\n'.format(*v)) 120 | for f in faces_as_list_of_nodes: 121 | debugFile.write('f ') 122 | for n in f: 123 | debugFile.write('{} '.format(n+1)) 124 | debugFile.write('\n') 125 | debugFile.close() 126 | 127 | # Store some info for the faces in a dict 128 | face_info = {} 129 | for fid, f in enumerate(faces_as_list_of_vertices): 130 | normal = mathutils.geometry.normal(f[0],f[1],f[2],f[3]) 131 | facecentre = mathutils.Vector((0,0,0)) 132 | for v in f: 133 | facecentre += 0.25*v 134 | face_info[fid] = {} 135 | face_info[fid]['normal'] = normal 136 | face_info[fid]['pos'] = [] 137 | face_info[fid]['neg'] = [] 138 | face_info[fid]['centre'] = facecentre 139 | 140 | connections_between_faces = [] 141 | # Find connections between faces, i.e. they share one edge 142 | for fid1, f1 in enumerate(faces_as_list_of_edges): 143 | for e in f1: 144 | for fid2, f2 in enumerate(faces_as_list_of_edges): 145 | if e in f2 and not fid1 == fid2: 146 | if not [min(fid1,fid2),max(fid1,fid2)] in connections_between_faces: 147 | connections_between_faces.append([min(fid1,fid2),max(fid1,fid2)]) 148 | 149 | #this is the most time consuming step 150 | # Use these connections to find cycles of connected faces; called faceLoops 151 | if numba: 152 | faceLoops_as_list_of_faces, faceLoops_as_list_of_connections = cycleFinderNumba.cycleFinder(connections_between_faces,range(len(faces_as_list_of_vertices))) 153 | else: 154 | faceLoops_as_list_of_faces, faceLoops_as_list_of_connections = cycleFinder(connections_between_faces,range(len(faces_as_list_of_vertices))) 155 | # faceLoops_as_list_of_faces, faceLoops_as_list_of_connections = blockBuilder2.cycleFinder(connections_between_faces,range(len(faces_as_list_of_vertices))) 156 | 157 | 158 | # Dig out block structures from these face loops 159 | block_as_faceLoop = [] 160 | for qf in faceLoops_as_list_of_faces: 161 | qf_is_a_block = True 162 | for n in faces_as_list_of_nodes[qf[0]]: 163 | if n in faces_as_list_of_nodes[qf[2]]: #if any of the vertices in face 0 is in face 2, this is not a block 164 | qf_is_a_block = False 165 | if qf_is_a_block: 166 | block_as_faceLoop.append(qf) 167 | # Get rid of block dublets - there are plenty 168 | faceLoops_nodes = [[] for i in range(len(block_as_faceLoop))] 169 | for qfid, qf in enumerate(block_as_faceLoop): 170 | for f in qf: 171 | for n in faces_as_list_of_nodes[f]: 172 | if not n in faceLoops_nodes[qfid]: 173 | faceLoops_nodes[qfid].append(n) 174 | for qf in faceLoops_nodes: 175 | qf.sort() 176 | tmp = [] 177 | potentialBlocks = [] # Each block is identified several times. Condense and put in potentialBlocks (list of vertices index) 178 | for qfid, qf in enumerate(faceLoops_nodes): 179 | if not qf in tmp: 180 | tmp.append(qf) 181 | if len(qf) == 8: 182 | potentialBlocks.append(block_as_faceLoop[qfid]) 183 | offences = [] 184 | block_centres = [] 185 | formalBlocks = [] 186 | dependent_edges = [] 187 | all_edges = [] 188 | if len(logFileName) > 0: 189 | logFile.write('number of potential blocks identified = ' + str(len(potentialBlocks)) + '\n') 190 | 191 | for b in potentialBlocks: 192 | is_a_real_block = True # more sanity checks soon... 193 | block = [] 194 | for n in faces_as_list_of_nodes[b[0]]: 195 | block.append(n) 196 | for n in faces_as_list_of_nodes[b[2]]: 197 | block.append(n) 198 | q2start = None 199 | for e in edges: # Locate the vertex just above block[0]. Store as q2start 200 | if block[0] == e[0]: 201 | if e[1] in block[4:8]: 202 | q2start = block.index(e[1]) 203 | if block[0] == e[1]: 204 | if e[0] in block[4:8]: 205 | q2start = block.index(e[0]) 206 | if q2start == None: # if not found above - this is not a complete block. 207 | q1nodes = block[0:4] 208 | q2nodes = block[4:-1] 209 | if len(logFileName) > 0: 210 | logFile.write('one block found was incomplete! ' + str(q1nodes) + str(q2nodes) + '\n') 211 | continue 212 | q2start = 0 #just set it to something. block wont be printed anyway 213 | quad1 = block[0:4] 214 | quad2 = [] 215 | for i in range(4): 216 | quad2.append(block[(i + q2start) % 4 + 4]) 217 | q1verts = [vertices_coord[quad1[0]],vertices_coord[quad1[1]],vertices_coord[quad1[2]],vertices_coord[quad1[3]]] 218 | q2verts = [vertices_coord[quad2[0]],vertices_coord[quad2[1]],vertices_coord[quad2[2]],vertices_coord[quad2[3]]] 219 | 220 | blockcentre = mathutils.Vector((0,0,0)) 221 | for n in block: 222 | blockcentre += 0.125*vertices_coord[n] 223 | q1fid, tmp = findFace(faces_as_list_of_nodes, quad1) 224 | q2fid, tmp = findFace(faces_as_list_of_nodes, quad2) 225 | 226 | normal1 = mathutils.geometry.normal(*q1verts) 227 | normal2 = mathutils.geometry.normal(*q2verts) 228 | 229 | facecentre1 = face_info[q1fid]['centre'] 230 | facecentre2 = face_info[q2fid]['centre'] 231 | direction1 = blockcentre-facecentre1 232 | direction2 = blockcentre-facecentre2 233 | 234 | v04 = q2verts[0] - q1verts[0] 235 | scalarProd1 = direction1.dot(normal1) 236 | scalarProd2 = direction2.dot(normal2) 237 | scalarProd3 = normal1.dot(v04) 238 | 239 | if scalarProd1*scalarProd2 > 0.: # make quad1 and quad2 rotate in the same direction 240 | quad2 = [quad2[0], quad2[-1], quad2[-2], quad2[-3]] 241 | normal2 *= -1.0 242 | 243 | if scalarProd3 < 0.: # Maintain righthanded system in each block 244 | tmp = list(quad2) 245 | quad2 = list(quad1) 246 | quad1 = tmp 247 | 248 | for nid,n in enumerate(quad1): #check that all edges are present 249 | if not (([n,quad2[nid]] in edges) or ([quad2[nid],n] in edges)): 250 | if len(logFileName) > 0: 251 | logFile.write('one block did not have all edges! ' + str(quad1) + str(quad2) + '\n') 252 | is_a_real_block = False 253 | break 254 | if not is_a_real_block: 255 | continue 256 | # more sanity... 257 | scale = v04.magnitude * normal1.magnitude 258 | if (abs(scalarProd3/scale) < 0.01): # abs(sin(alpha)) < 0.01, where alpha is angle for normal1 and v04 259 | if len(logFileName) > 0: 260 | logFile.write('flat block ruled out!' + str(quad1) + str(quad2) + '\n') 261 | continue 262 | 263 | if is_a_real_block: # this write-out only works if blenders own vertex numbering starts at zero!! seems to work... 264 | offences.append(0) 265 | block_centres.append(blockcentre) 266 | 267 | vl = quad1 + quad2 268 | formalBlocks.append(vl) # list of verts defining the block in correct order 269 | # formalBlocks are blocks that hava formal block structure and are not flat. Still in an O-mesh there are more formal 270 | # blocks present than what we want. More filtering... 271 | 272 | for bid, vl in enumerate(formalBlocks): 273 | fs = [] 274 | fs.append(vl[0:4]) 275 | fs.append(vl[4:8]) 276 | fs.append([vl[0], vl[1], vl[5], vl[4]]) 277 | fs.append([vl[1], vl[2], vl[6], vl[5]]) 278 | fs.append([vl[2], vl[3], vl[7], vl[6]]) 279 | fs.append([vl[3], vl[0], vl[4], vl[7]]) 280 | blockcentre = block_centres[bid] 281 | for f in fs: 282 | fid, tmp = findFace(faces_as_list_of_nodes, f) 283 | normal = face_info[fid]['normal'] 284 | facecentre = face_info[fid]['centre'] 285 | direction = normal.dot((blockcentre-facecentre)) 286 | if direction >= 0.: 287 | face_info[fid]['pos'].append(bid) 288 | else: 289 | face_info[fid]['neg'].append(bid) 290 | for f in face_info: # Not more than two blocks on each side of a face. If a block scores too high in 'offences' it will be ruled out 291 | if len(face_info[f]['pos'])>1: 292 | for bid in face_info[f]['pos']: 293 | offences[bid] += 1 294 | if len(face_info[f]['neg'])>1: 295 | for bid in face_info[f]['neg']: 296 | offences[bid] += 1 297 | block_print_out = [] 298 | for bid, vl in enumerate(formalBlocks): 299 | if offences[bid] <= 3 and not all( v in disabled for v in vl ): 300 | block_print_out.append(vl) 301 | i_edges = [edge(vl[0],vl[1]), edge(vl[2],vl[3]), edge(vl[4],vl[5]), edge(vl[6],vl[7])] 302 | j_edges = [edge(vl[1],vl[2]), edge(vl[3],vl[0]), edge(vl[5],vl[6]), edge(vl[7],vl[4])] 303 | k_edges = [edge(vl[0],vl[4]), edge(vl[1],vl[5]), edge(vl[2],vl[6]), edge(vl[3],vl[7])] 304 | # i_edges = [[vl[0],vl[1]], [vl[2],vl[3]], [vl[4],vl[5]], [vl[6],vl[7]]] 305 | # j_edges = [[vl[1],vl[2]], [vl[3],vl[0]], [vl[5],vl[6]], [vl[7],vl[4]]] 306 | # k_edges = [[vl[0],vl[4]], [vl[1],vl[5]], [vl[2],vl[6]], [vl[3],vl[7]]] 307 | dependent_edges.append(i_edges) #these 4 edges have the same resolution 308 | dependent_edges.append(j_edges) #these 4 edges have the same resolution 309 | dependent_edges.append(k_edges) #these 4 edges have the same resolution 310 | for e in range(4): 311 | if not i_edges[e] in all_edges: 312 | all_edges.append(i_edges[e]) 313 | if not j_edges[e] in all_edges: 314 | all_edges.append(j_edges[e]) 315 | if not k_edges[e] in all_edges: 316 | all_edges.append(k_edges[e]) 317 | else: # Dont let non-allowed blocks to stop definition of patch names 318 | for f in face_info: 319 | if bid in face_info[f]['pos']: 320 | ind = face_info[f]['pos'].index(bid) 321 | face_info[f]['pos'].pop(ind) 322 | if bid in face_info[f]['neg']: 323 | ind = face_info[f]['neg'].index(bid) 324 | face_info[f]['neg'].pop(ind) 325 | # stime = time.time() 326 | #this is the second most time consuming step 327 | still_coupling = True 328 | while still_coupling: 329 | still_coupling = couple_edges(dependent_edges) 330 | # blockBuilder2.couple_edges(dependent_edges) 331 | # print('still coupling, t',time.time() - stime) 332 | 333 | for es, edgeSet in enumerate(dependent_edges): # remove duplicates in lists 334 | dependent_edges[es] = removedup(edgeSet) 335 | return logFile, block_print_out, dependent_edges, face_info, all_edges, faces_as_list_of_nodes 336 | 337 | -------------------------------------------------------------------------------- /blockMeshBodyFit.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import os 3 | import numpy as np 4 | import subprocess 5 | import shutil 6 | import itertools 7 | import glob 8 | from . import utils 9 | class PreviewMesh(): 10 | def __init__(self, folder=None): 11 | if shutil.which('blockMeshBodyFit'): 12 | self.blockMeshbin = 'blockMeshBodyFit' 13 | elif shutil.which('blockMeshBoyFit'): 14 | self.blockMeshbin = 'blockMeshBoyFit' 15 | else: 16 | raise RuntimeError('ERROR: No BlockMeshBodyFit Found!') 17 | if folder: 18 | if not os.path.isdir(folder): 19 | os.mkdir(folder) 20 | if not os.path.isdir(folder+'/constant'): 21 | os.mkdir(folder+'/constant') 22 | if not os.path.isdir(folder+'/constant/triSurface'): 23 | os.mkdir(folder+'/constant/triSurface') 24 | if not os.path.isdir(folder+'/system'): 25 | os.mkdir(folder+'/system') 26 | self.blockMeshDictPath = folder+ '/system/blockMeshDict' 27 | self.triSurfacePath = folder+'/constant/triSurface' 28 | else: 29 | self.tempdir = tempfile.mkdtemp() 30 | self.blockMeshDictPath = self.tempdir+"/constant/polyMesh/blockMeshDict" 31 | os.mkdir(self.tempdir+'/constant') 32 | os.mkdir(self.tempdir+'/constant/polyMesh') 33 | self.triSurfacePath = self.tempdir+'/constant/triSurface' 34 | os.mkdir(self.triSurfacePath) 35 | os.mkdir(self.tempdir+'/system') 36 | os.mkdir(self.tempdir+'/0') 37 | cd = open(self.tempdir+'/system/controlDict','w') 38 | cd.write(self.header()) 39 | print('OpenFOAM temp directory: {}'.format(self.tempdir)) 40 | 41 | def writeBlockMeshDict(self, verts, convertToMeters, boundaries, polyLines, edgeInfo, blockNames, blocks, dependent_edges, projections, searchLength): 42 | bmFile = open(self.blockMeshDictPath,'w') 43 | bmFile.write(self.header()) 44 | bmFile.write("\nconvertToMeters " + str(convertToMeters) + ";\n") 45 | bmFile.write("\nsearchLength {};\n\n\nvertices\n(\n".format(searchLength)) 46 | 47 | for v in verts: 48 | bmFile.write(' ({} {} {})\n'.format(*v)) 49 | bmFile.write(");\nblocks\n(\n") 50 | NoCells = 0 51 | 52 | edge = lambda e0,e1: [min(e0,e1), max(e0,e1)] 53 | 54 | for bid, (vl, blockName) in enumerate(zip(blocks, blockNames)): 55 | edges = [(vl[e[0]],vl[e[1]]) for e in [(0,1),(3,2),(7,6),(4,5),(0,3),(1,2),(5,6),(4,7),(0,4),(1,5),(2,6),(3,7)]] 56 | gradingStr = "" 57 | for ei in edges: 58 | e = edgeInfo[ei] 59 | gradingStr+= '{:.6g} '.format(e["ratio"]) 60 | ires = edgeInfo[edges[0]]["N"] 61 | jres = edgeInfo[edges[4]]["N"] 62 | kres = edgeInfo[edges[8]]["N"] 63 | 64 | NoCells += ires*jres*kres 65 | bmFile.write('// block id {} \nhex ({} {} {} {} {} {} {} {}) '.format(bid,*vl) \ 66 | + blockName + ' ({} {} {}) '.format(ires,jres,kres)\ 67 | + 'edgeGrading (' + gradingStr + ')\n' ) 68 | 69 | snapFaces = dict() 70 | for key,value in projections['face2surf'].items(): 71 | if value not in snapFaces: 72 | snapFaces[value] = [] 73 | snapFaces[value].append(key) 74 | bmFile.write(');\n\nsnapFaces\n{\n') 75 | for key, value in snapFaces.items(): 76 | bmFile.write(' %s.stl\n {\n faces\n (\n'%key) 77 | for v in value: 78 | bmFile.write(' ({} {} {} {})\n'.format(*v)) 79 | bmFile.write(' );\n }\n') 80 | 81 | bmFile.write('};\n\npatches\n(\n') 82 | for b in boundaries: 83 | bmFile.write(' {} {}\n (\n'.format(b['type'],b['name'] )) 84 | for v in b['faceVerts']: 85 | bmFile.write(' ({} {} {} {})\n'.format(*v)) 86 | bmFile.write(' )\n') 87 | bmFile.write(');\n\nedges\n(\n') 88 | for pl in polyLines: 89 | bmFile.write(pl) 90 | bmFile.write(');') 91 | bmFile.close() 92 | return NoCells 93 | 94 | 95 | def readHeader(self,dicfile): 96 | numberOfFields = 0 97 | startLine = False 98 | with open(dicfile) as fin: 99 | for lidx,line in enumerate(fin): 100 | if not numberOfFields: 101 | try: 102 | numberOfFields = int(line) 103 | except ValueError: 104 | pass 105 | if '(' in line: 106 | startLine = lidx + 1 107 | break 108 | return startLine, numberOfFields 109 | 110 | def readBoundaries(self,files): 111 | data = [] 112 | readingField = False 113 | for line in files: 114 | if not line.strip(): 115 | continue 116 | if not readingField and line.strip() == '{': 117 | readingField = True 118 | elif not readingField: 119 | temp = dict() 120 | temp['name']= line.strip() 121 | elif readingField and 'type' in line: 122 | temp['type'] = line.strip().split()[1][:-1] 123 | elif readingField and 'nFaces' in line: 124 | temp['nFaces'] = int(line.strip().split()[1][:-1]) 125 | elif readingField and 'startFace' in line: 126 | temp['startFace'] = int(line.strip().split()[1][:-1]) 127 | elif readingField and line.strip() == '}': 128 | data.append(temp) 129 | readingField = False 130 | elif not readingField and line.strip() == ')': 131 | break 132 | return data 133 | 134 | def getPoints(self,faces=None): 135 | pointsFile = self.tempdir +'/constant/polyMesh/points' 136 | startLine, numberofLines = self.readHeader(pointsFile) 137 | convertfnc1 = lambda x: float(x[1:]) 138 | convertfnc2 = lambda x:float(x[:-1]) 139 | with open(pointsFile,'rb') as fin: 140 | points = np.genfromtxt(itertools.islice(fin,startLine,startLine+numberofLines),\ 141 | converters={0:convertfnc1,2:convertfnc2},dtype=float) 142 | if faces!=None: 143 | pidxs = np.unique(np.ravel(faces)) 144 | points = points[pidxs] 145 | points=points.tolist() 146 | return points 147 | 148 | def getFaces(self): 149 | facesFile = self.tempdir +'/constant/polyMesh/faces' 150 | startLine, numberofLines = self.readHeader(facesFile) 151 | convertfnc1 = lambda x: int(x[2:]) 152 | convertfnc2 = lambda x: int(x[:-1]) 153 | with open(facesFile,'rb') as fin: 154 | faces = np.genfromtxt(itertools.islice(fin,startLine,startLine+numberofLines),\ 155 | converters={0:convertfnc1,3:convertfnc2},dtype=int) 156 | faces = faces.tolist() 157 | return faces 158 | 159 | def getBCFaces(self,internalCells): 160 | faces = self.getFaces() 161 | bcifaces = faces 162 | bcfaces = faces 163 | if not internalCells: 164 | boundaryFile = self.tempdir + '/constant/polyMesh/boundary' 165 | startLine, boundaries = self.readHeader(boundaryFile) 166 | with open(boundaryFile) as fin: 167 | fields = self.readBoundaries(itertools.islice(fin,startLine,None)) 168 | self.fields = fields 169 | bcifaces = [] 170 | bcfaces=[] 171 | for bc in sorted(fields, key=lambda k: k['startFace']): 172 | bcfaces.extend(faces[bc['startFace']:bc['startFace']+bc['nFaces']]) 173 | bcifaces = np.array(bcfaces,dtype=int) 174 | bcifaces = np.unique(bcifaces.ravel(),return_inverse=True)[1].reshape(bcifaces.shape) 175 | bcifaces = bcifaces.astype(int).tolist() 176 | return bcfaces,bcifaces 177 | 178 | #this is faster 179 | def getBCFaces2(self,internalCells): 180 | facesFile = self.tempdir +'/constant/polyMesh/faces' 181 | startLine, numberofLines = self.readHeader(facesFile) 182 | faces = open(facesFile).readlines() 183 | faces = faces[startLine:startLine+numberofLines] 184 | subs = lambda s: list(map(int,s.__getitem__(slice(2,-2)).split())) 185 | faces = list(map(subs, faces)) 186 | boundaryFile = self.tempdir + '/constant/polyMesh/boundary' 187 | startLine, boundaries = self.readHeader(boundaryFile) 188 | with open(boundaryFile) as fin: 189 | fields = self.readBoundaries(itertools.islice(fin,startLine,None)) 190 | self.fields = fields 191 | bcifaces = [] 192 | bcfaces=[] 193 | for bc in sorted(fields, key=lambda k: k['startFace']): 194 | bcfaces.extend(faces[bc['startFace']:bc['startFace']+bc['nFaces']]) 195 | bcifaces = np.array(bcfaces,dtype=int) 196 | bcifaces = np.unique(bcifaces.ravel(),return_inverse=True)[1].reshape(bcifaces.shape) 197 | bcifaces = bcifaces.astype(int).tolist() 198 | return bcfaces,bcifaces 199 | 200 | def runBlockMesh(self): 201 | subprocess.call([self.blockMeshbin,'-case',self.tempdir],stdout=subprocess.PIPE) 202 | 203 | def runMesh(self,runBlockMesh=True,internalCells=False): 204 | print('running blockmesh') 205 | if runBlockMesh: 206 | self.runBlockMesh() 207 | faces, bcifaces=self.getBCFaces2(internalCells) 208 | points=self.getPoints(faces) 209 | # shutil.rmtree(self.tempdir) 210 | return points, bcifaces 211 | 212 | def header(self): 213 | return \ 214 | ''' 215 | /*--------------------------------*- C++ -*----------------------------------*/ 216 | 217 | // File was generated by SwiftBlock, a Blender 3D addon. 218 | 219 | FoamFile 220 | { 221 | version 2.0; 222 | format ascii; 223 | class dictionary; 224 | object blockMeshDict; 225 | } 226 | // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 227 | 228 | 229 | deltaT 1; 230 | 231 | writeInterval 1; 232 | 233 | 234 | 235 | // ************************************************************************* // 236 | 237 | ''' 238 | -------------------------------------------------------------------------------- /blockMeshMG.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import os 3 | import numpy as np 4 | import subprocess 5 | import shutil 6 | import itertools 7 | import glob 8 | from . import utils 9 | class PreviewMesh(): 10 | def __init__(self, folder=None): 11 | if not shutil.which('blockMesh'): 12 | raise RuntimeError('ERROR: No BlockMesh Found!') 13 | else: 14 | self.blockMeshbin = 'blockMesh' 15 | if folder: 16 | if not os.path.isdir(folder): 17 | os.mkdir(folder) 18 | if not os.path.isdir(folder+'/constant'): 19 | os.mkdir(folder+'/constant') 20 | if not os.path.isdir(folder+'/constant/geometry'): 21 | os.mkdir(folder+'/constant/geometry') 22 | if not os.path.isdir(folder+'/system'): 23 | os.mkdir(folder+'/system') 24 | self.blockMeshDictPath = folder + '/system/blockMeshDict' 25 | self.geomPath = folder+'/constant/geometry' 26 | else: 27 | self.tempdir = tempfile.mkdtemp() 28 | self.blockMeshDictPath = self.tempdir+"/system/blockMeshDict" 29 | os.mkdir(self.tempdir+'/constant') 30 | os.mkdir(self.tempdir+'/constant/polyMesh') 31 | self.geomPath = self.tempdir+'/constant/geometry' 32 | os.mkdir(self.geomPath) 33 | os.mkdir(self.tempdir+'/system') 34 | os.mkdir(self.tempdir+'/0') 35 | cd = open(self.tempdir+'/system/controlDict','w') 36 | cd.write(self.header()) 37 | print('OpenFOAM temp directory: {}'.format(self.tempdir)) 38 | 39 | def writeBlockMeshDict(self, verts, convertToMeters, boundaries, polyLines, edgeInfo, blockNames, blocks, dependent_edges,\ 40 | projections): 41 | bmFile = open(self.blockMeshDictPath,'w') 42 | bmFile.write(self.header()) 43 | bmFile.write('\ngeometry\n{\n') 44 | for g in projections['geo']: 45 | bmFile.write(' {geo}\n {{\n type triSurfaceMesh;\n file "{geo}.stl";\n }}\n'.format(geo=g)) 46 | 47 | bmFile.write("}\nvertices\n(\n") 48 | for i,v in enumerate(verts): 49 | if i in projections['vert2surf']: 50 | bmFile.write(' project ({} {} {}) ({})\n'.format(*v,projections['vert2surf'][i])) 51 | else: 52 | bmFile.write(' ({} {} {})\n'.format(*v)) 53 | 54 | bmFile.write(");\nedges\n(\n") 55 | for key, value in projections['edge2surf'].items(): 56 | bmFile.write(' projectCurve {} {} ({})\n'.format(*key, value)) 57 | for pl in polyLines: 58 | bmFile.write(pl) 59 | 60 | bmFile.write(");\nfaces\n(\n") 61 | for key, value in projections['face2surf'].items(): 62 | # for v in value: 63 | bmFile.write(' project ({} {} {} {}) {}\n'.format(*key,value)) 64 | 65 | bmFile.write(");\nblocks\n(\n") 66 | 67 | 68 | NoCells = 0 69 | for bid, (vl, blockName) in enumerate(zip(blocks, blockNames)): 70 | edges = [(vl[e[0]],vl[e[1]]) for e in [(0,1),(3,2),(7,6),(4,5),(0,3),(1,2),(5,6),(4,7),(0,4),(1,5),(2,6),(3,7)]] 71 | gradingStr = "" 72 | for ei in edges: 73 | e = edgeInfo[ei] 74 | gradingStr+='\n(\n ({:.6g} {:.6g} {:.6g}) ({:.6g} {:.6g} {:.6g}) ({:.6g} {:.6g} {:.6g}) '.format( 75 | e["l1"],e["n1"],e["ratio1"],\ 76 | e["dL"],e["nL"],1,\ 77 | e["l2"],e["n2"],1/e["ratio2"]) + '\n)' 78 | ires = edgeInfo[edges[0]]["N"] 79 | jres = edgeInfo[edges[4]]["N"] 80 | kres = edgeInfo[edges[8]]["N"] 81 | 82 | NoCells += ires*jres*kres 83 | bmFile.write('// block id {} \nhex ({} {} {} {} {} {} {} {}) '.format(bid,*vl) \ 84 | + blockName + ' ({} {} {}) '.format(ires,jres,kres)\ 85 | + 'edgeGrading (' + gradingStr + '\n)\n' ) 86 | bmFile.write(');\n\npatches\n(\n') 87 | for b in boundaries: 88 | bmFile.write(' {} {}\n (\n'.format(b['type'],b['name'] )) 89 | for v in b['faceVerts']: 90 | bmFile.write(' ({} {} {} {})\n'.format(*v)) 91 | bmFile.write(' )\n') 92 | bmFile.write(');') 93 | bmFile.close() 94 | return NoCells 95 | 96 | 97 | def readHeader(self,dicfile): 98 | numberOfFields = 0 99 | startLine = False 100 | with open(dicfile) as fin: 101 | for lidx,line in enumerate(fin): 102 | if not numberOfFields: 103 | try: 104 | numberOfFields = int(line) 105 | except ValueError: 106 | pass 107 | if '(' in line: 108 | startLine = lidx + 1 109 | break 110 | return startLine, numberOfFields 111 | 112 | def readBoundaries(self,files): 113 | data = [] 114 | readingField = False 115 | for line in files: 116 | if not line.strip(): 117 | continue 118 | if not readingField and line.strip() == '{': 119 | readingField = True 120 | elif not readingField: 121 | temp = dict() 122 | temp['name']= line.strip() 123 | elif readingField and 'type' in line: 124 | temp['type'] = line.strip().split()[1][:-1] 125 | elif readingField and 'nFaces' in line: 126 | temp['nFaces'] = int(line.strip().split()[1][:-1]) 127 | elif readingField and 'startFace' in line: 128 | temp['startFace'] = int(line.strip().split()[1][:-1]) 129 | elif readingField and line.strip() == '}': 130 | data.append(temp) 131 | readingField = False 132 | elif not readingField and line.strip() == ')': 133 | break 134 | return data 135 | 136 | def getPoints(self,faces=None): 137 | pointsFile = self.tempdir +'/constant/polyMesh/points' 138 | startLine, numberofLines = self.readHeader(pointsFile) 139 | convertfnc1 = lambda x: float(x[1:]) 140 | convertfnc2 = lambda x:float(x[:-1]) 141 | with open(pointsFile,'rb') as fin: 142 | points = np.genfromtxt(itertools.islice(fin,startLine,startLine+numberofLines),\ 143 | converters={0:convertfnc1,2:convertfnc2},dtype=float) 144 | if faces!=None: 145 | pidxs = np.unique(np.ravel(faces)) 146 | points = points[pidxs] 147 | points=points.tolist() 148 | return points 149 | 150 | def getFaces(self): 151 | facesFile = self.tempdir +'/constant/polyMesh/faces' 152 | startLine, numberofLines = self.readHeader(facesFile) 153 | convertfnc1 = lambda x: int(x[2:]) 154 | convertfnc2 = lambda x: int(x[:-1]) 155 | with open(facesFile,'rb') as fin: 156 | faces = np.genfromtxt(itertools.islice(fin,startLine,startLine+numberofLines),\ 157 | converters={0:convertfnc1,3:convertfnc2},dtype=int) 158 | faces = faces.tolist() 159 | return faces 160 | 161 | def getBCFaces(self,internalCells): 162 | faces = self.getFaces() 163 | bcifaces = faces 164 | bcfaces = faces 165 | if not internalCells: 166 | boundaryFile = self.tempdir + '/constant/polyMesh/boundary' 167 | startLine, boundaries = self.readHeader(boundaryFile) 168 | with open(boundaryFile) as fin: 169 | fields = self.readBoundaries(itertools.islice(fin,startLine,None)) 170 | self.fields = fields 171 | bcifaces = [] 172 | bcfaces=[] 173 | for bc in sorted(fields, key=lambda k: k['startFace']): 174 | bcfaces.extend(faces[bc['startFace']:bc['startFace']+bc['nFaces']]) 175 | bcifaces = np.array(bcfaces,dtype=int) 176 | bcifaces = np.unique(bcifaces.ravel(),return_inverse=True)[1].reshape(bcifaces.shape) 177 | bcifaces = bcifaces.astype(int).tolist() 178 | return bcfaces,bcifaces 179 | 180 | #this is faster 181 | def getBCFaces2(self,internalCells): 182 | facesFile = self.tempdir +'/constant/polyMesh/faces' 183 | startLine, numberofLines = self.readHeader(facesFile) 184 | faces = open(facesFile).readlines() 185 | faces = faces[startLine:startLine+numberofLines] 186 | subs = lambda s: list(map(int,s.__getitem__(slice(2,-2)).split())) 187 | faces = list(map(subs, faces)) 188 | boundaryFile = self.tempdir + '/constant/polyMesh/boundary' 189 | startLine, boundaries = self.readHeader(boundaryFile) 190 | with open(boundaryFile) as fin: 191 | fields = self.readBoundaries(itertools.islice(fin,startLine,None)) 192 | self.fields = fields 193 | bcifaces = [] 194 | bcfaces=[] 195 | for bc in sorted(fields, key=lambda k: k['startFace']): 196 | bcfaces.extend(faces[bc['startFace']:bc['startFace']+bc['nFaces']]) 197 | bcifaces = np.array(bcfaces,dtype=int) 198 | bcifaces = np.unique(bcifaces.ravel(),return_inverse=True)[1].reshape(bcifaces.shape) 199 | bcifaces = bcifaces.astype(int).tolist() 200 | return bcfaces,bcifaces 201 | 202 | def runBlockMesh(self): 203 | subprocess.call([self.blockMeshbin,'-case',self.tempdir],stdout=subprocess.PIPE) 204 | 205 | def runMesh(self,runBlockMesh=True,internalCells=False): 206 | print('running blockmesh') 207 | if runBlockMesh: 208 | self.runBlockMesh() 209 | faces, bcifaces=self.getBCFaces2(internalCells) 210 | points=self.getPoints(faces) 211 | shutil.rmtree(self.tempdir) 212 | return points, bcifaces 213 | 214 | def header(self): 215 | return \ 216 | ''' 217 | /*--------------------------------*- C++ -*----------------------------------*/ 218 | 219 | // File was generated by SwiftBlock, a Blender 3D addon. 220 | 221 | FoamFile 222 | { 223 | version 2.0; 224 | format ascii; 225 | class dictionary; 226 | object blockMeshDict; 227 | } 228 | // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 229 | 230 | deltaT 1; 231 | 232 | writeInterval 1; 233 | 234 | 235 | 236 | // ************************************************************************* // 237 | 238 | ''' 239 | -------------------------------------------------------------------------------- /cycleFinderNumba.py: -------------------------------------------------------------------------------- 1 | from numba import jit 2 | import numpy as np 3 | 4 | # @jit(nopython=True) 5 | def still_coupling(dependent_edges): 6 | for es0 in range(len(dependent_edges)): 7 | edgeSet0 = dependent_edges[es0] 8 | for edge in edgeSet0: 9 | for es1 in range(len(dependent_edges)): 10 | edgeSet1 = dependent_edges[es1] 11 | if edge in edgeSet1 and es0 != es1: 12 | for e in edgeSet0: 13 | edgeSet1.append(e) 14 | dependent_edges.pop(es0) 15 | return True 16 | return False 17 | 18 | def couple_edges(dependent_edges): 19 | while still_coupling(dependent_edges): 20 | pass 21 | 22 | def cycleFinder(edges,verts): 23 | verticesId = np.array(verts) 24 | edges = np.array(edges) 25 | edgeVisited = np.zeros(len(edges), dtype=bool) 26 | faces = [-1] # For Numba the arrays have to contain element 27 | facesEdges = [-1] 28 | no_edges = 0 29 | 30 | # 50 is the limit of vertices in one edge. Should be enough, maybe too many? 31 | v_in_edge = np.ones((len(verticesId),50),dtype=int) * -1 32 | for v in verticesId: 33 | for eid, e in enumerate(edges): 34 | if v in e: 35 | v_in_edge[v][np.where(v_in_edge[v] == -1)[0][0]] = eid 36 | 37 | run(verticesId,edges,edgeVisited,faces,facesEdges,no_edges, v_in_edge) 38 | 39 | # Clean double faces 40 | faces = np.reshape(faces[1:],(-1,4)) 41 | temp, u = np.unique(np.sort(faces), axis=0, return_index=True) 42 | faces = faces[u] 43 | facesP = [list(map(np.asscalar,f)) for f in faces] 44 | 45 | facesEdges = np.reshape(facesEdges[1:],(-1,4)) 46 | facesEdges = facesEdges[u] 47 | facesEdgesP = [list(map(np.asscalar,f)) for f in facesEdges] 48 | 49 | return facesP, facesEdgesP 50 | 51 | @jit(nopython=True) 52 | def run(verticesId,edges,edgeVisited,faces,facesEdges,no_edges, v_in_edge): 53 | for v in verticesId: 54 | currentCycle = [v] 55 | currentCycleEdges = [-1] 56 | buildFourEdgeFaces(v, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges, v_in_edge, first=True) 57 | 58 | @jit(nopython=True) 59 | def buildFourEdgeFaces(v, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges, v_in_edge, first=False): 60 | for eid in v_in_edge[v]: 61 | if eid == -1: 62 | break 63 | e = edges[eid] 64 | if v == e[0]: 65 | opposite_v = e[1] 66 | elif v == e[1]: 67 | opposite_v = e[0] 68 | else: 69 | continue 70 | if not edgeVisited[eid]: 71 | no_edges += 1 72 | edgeVisited[eid] = True 73 | currentCycle.append(opposite_v) 74 | if first: 75 | currentCycleEdges[0] = eid 76 | first = False 77 | else: 78 | currentCycleEdges.append(eid) 79 | if currentCycle[0] == currentCycle[-1]: # First equals last -> we have a face 80 | # we are only interested in quads 81 | if len(currentCycle) == 5: 82 | faces.extend(currentCycle[0:4]) 83 | facesEdges.extend(currentCycleEdges[0:4]) 84 | else: 85 | if no_edges < 4: 86 | buildFourEdgeFaces(opposite_v, edgeVisited, edges, no_edges, currentCycle, currentCycleEdges, faces, facesEdges, v_in_edge) 87 | no_edges -= 1 88 | currentCycle.pop() 89 | currentCycleEdges.pop() 90 | edgeVisited[eid] = False 91 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import numpy as np 3 | 4 | def edgeMapping(edge): 5 | if edge["type"] == "Geometric MG": 6 | return multiGrading(edge) 7 | elif edge["type"] == "Geometric": 8 | edge["ratio"] == edge["ratio"] 9 | return edge 10 | 11 | def multiGrading(edge): 12 | eps = 1e-6 13 | grading1 = True 14 | grading2 = True 15 | x1,x2 = edge['x1'], edge['x2'] 16 | r1,r2 = edge['r1'], edge['r2'] 17 | N, L = edge['N'], edge['L'] 18 | 19 | def both(L,N,x1,x2,r1,r2,dx): 20 | n1 = np.log(dx/x1) / np.log(r1) + 1 21 | n2 = np.log(dx/x2) / np.log(r2) + 1 22 | l1 = x1*(1-r1**n1)/(1-r1) 23 | l2 = x2*(1-r2**n2)/(1-r2) 24 | Lapprox = l1 + l2 + (N - n1 - n2-1)*dx 25 | err = (L-Lapprox) 26 | return err,(n1,n2,l1,l2) 27 | 28 | def oneside(L,N,x,r,dx): 29 | n = np.log(dx/x) / np.log(r) + 1 30 | l = x*(1-r**n)/(1-r) 31 | Lapprox = l + (N - n)*dx 32 | err = (L-Lapprox) 33 | return err,(n,l) 34 | 35 | if abs(x1) < eps or (abs(r1) - 1) < eps: 36 | grading1 = False 37 | if abs(x2) < eps or (abs(r2) - 1) < eps: 38 | grading2 = False 39 | 40 | if not grading1 and not grading2: 41 | edge["l1"], edge["l2"] = 0,0 42 | edge["n1"], edge["n2"] = 0,0 43 | edge["ratio1"], edge["ratio2"] = 1,1 44 | edge["dL"], edge["nL"] = 1, N 45 | return edge 46 | 47 | elif grading1 and not grading2: 48 | l1 = x1*(1-r1**N)/(1-r1) 49 | if l1 < L: 50 | n1 = np.log(1-l1/x1*(1-r1))/np.log(r1) 51 | n1 += 1 52 | dx = x1*r1**n1 53 | edge["l1"], edge["l2"] = L,0 54 | edge["n1"], edge["n2"] = n1,0 55 | edge["ratio1"], edge["ratio2"] = dx/x1,1 56 | edge["dL"], edge["nL"] = 0, 0 57 | return edge 58 | approx = oneside 59 | x,r = x1,r1 60 | dx = L/N #initial guess 61 | parameters = [L,N,x,r,dx] 62 | elif not grading1 and grading2: 63 | l2 = x2*(1-r2**N)/(1-r2) 64 | if l2 < L: 65 | n2 = np.log(1-l2/x2*(1-r2))/np.log(r2) 66 | n2 += 1 67 | dx = x2*r2**n2 68 | edge["l1"], edge["l2"] = 0,L 69 | edge["n1"], edge["n2"] = 0,n2 70 | edge["ratio1"], edge["ratio2"] = 1,dx/x2 71 | edge["dL"], edge["nL"] = 0, 0 72 | return edge 73 | approx = oneside 74 | x,r = x2,r2 75 | dx = L/N 76 | parameters = [L,N,x,r,dx] 77 | else: 78 | n1 = (np.log(x2/x1)+N*np.log(r2))/np.log(r1*r2) 79 | n1 = int(n1+0.5) 80 | n2 = N-n1-1 81 | l1 = x1*((1-r1**n1)/(1-r1)) 82 | l2 = x2*((1-r2**n2)/(1-r2)) 83 | if (l1+l2) < L: 84 | n1 = np.log((L*(1-r1)*(1-r2)-x1-x2+x1*r2+x2*r1)/(-2*x1+x1*r1+x1*r2))/np.log(r1) 85 | n2 = np.log(x1/x2*r1**n1)/np.log(r2) 86 | l1 = x1*((1-r1**n1)/(1-r1)) 87 | l2 = x2*((1-r2**n2)/(1-r2)) 88 | dx = x1*r1**n1 89 | n1 += 1 90 | n2 += 1 91 | edge["l1"], edge["l2"] = l1,l2 92 | edge["n1"], edge["n2"] = n1,n2 93 | edge["ratio1"], edge["ratio2"] = dx/x1, dx/x2 94 | edge["dL"], edge["nL"] = 0, 0 95 | return edge 96 | # l2 = (x2-x1+L-L*r1)/(2-r2-r1) 97 | # l1 = L - l2 98 | # n1 = np.log(1-l1/x1*(1-r1))/np.log(r1) 99 | # n2 = N-n1 100 | approx = both 101 | dx = L/N 102 | parameters = [L,N,x1,x2,r1,r2,dx] 103 | 104 | 105 | Lapprox = 0.0 106 | err = 1.0 107 | count = 0 108 | 109 | err,pars=approx(*parameters) 110 | dx_old = dx 111 | err_old = err 112 | dx = dx*1.2*1e-10 # small perturbation 113 | parameters[-1] = dx 114 | err,pars=approx(*parameters) 115 | 116 | while abs(err)>1e-12 and count < 1000: 117 | dx_temp = dx 118 | derr = (err - err_old)/(dx - dx_old) 119 | dx = dx - err/derr 120 | dx_old = dx_temp 121 | err_old = err 122 | parameters[-1] = dx 123 | err, out = approx(*parameters) 124 | count = count+1 125 | 126 | if grading1 and not grading2: 127 | n1,l1 = out 128 | ratio1 = dx/x1 129 | n2,l2,ratio2 = 0,0,1 130 | elif not grading1 and grading2: 131 | n2,l2 = out 132 | ratio2 = dx/x2 133 | n1,l1,ratio1 = 0,0,1 134 | else: 135 | n1,n2,l1,l2 = out 136 | ratio1 = dx/x1 137 | ratio2 = dx/x2 138 | 139 | if (dx < x1 and abs(x1) > eps) or (dx < x2 and abs(x2) > eps): 140 | dx = x1 141 | l1, l2 = 0,0 142 | n1, n2 = 0,0 143 | ratio1, ratio2 = 1, 1 144 | 145 | dL = L-l1-l2 146 | nL = N-n1-n2 147 | dx = dL/nL 148 | edge['l1'], edge['l2'] = l1, l2 149 | edge['n1'], edge['n2'] = n1, n2 150 | edge['ratio1'], edge['ratio2'] = ratio1, ratio2 151 | edge['dL'], edge['nL'] = dL, nL 152 | return edge 153 | 154 | def getNodes(x1,x2,r1,r2,L,dx): 155 | n1 = np.log(dx/x1)/np.log(r1) + 1 156 | n2 = np.log(dx/x1)/np.log(r1) + 1 157 | l1 = x1*(1-r1**n1)/(1-r1) 158 | l2 = x2*(1-r2**n2)/(1-r2) 159 | if (l1+l2) > L: 160 | n1 = np.log((L*(1-r1)*(1-r2)-x1-x2+x1*r2+x2*r1)/(-2*x1+x1*r1+x1*r2))/np.log(r1) 161 | n1 = int(n1+0.5)+1 162 | n2 = np.log(x1/x2*r1**n1)/np.log(r2) 163 | n2 = int(n2+0.5) 164 | l1 = x1*((1-r1**n1)/(1-r1)) 165 | l2 = x2*((1-r2**n2)/(1-r2)) 166 | dx = x1*r1**n1 167 | return n1+n2 168 | else: 169 | return n1+n2+(L-l1-l2)/dx 170 | 171 | def edge(e0, e1): 172 | return [min(e0,e1), max(e0,e1)] 173 | 174 | def findFace(faces, vl): 175 | for fid, f in enumerate(faces): 176 | if vl[0] in f and vl[1] in f and vl[2] in f and vl[3] in f: 177 | return fid, f 178 | return -1, [] 179 | 180 | 181 | # No comments. Just works. 182 | def getEdgeDirections(block_print_out, dependent_edges): 183 | edgeDirections = [set() for i in dependent_edges] 184 | positiveBlockEdges = [[(0,1),(3,2),(7,6),(4,5)],[(0,3),(1,2),(5,6),(4,7)],[(0,4),(1,5),(2,6),(3,7)]] 185 | for i in range(1000): 186 | ready = True 187 | for ed, de in zip(edgeDirections,dependent_edges): 188 | if not len(ed)==len(de): 189 | ready = False 190 | if ready: 191 | break 192 | for bid, vl in enumerate(block_print_out): 193 | for es, edgeSet in enumerate(dependent_edges): 194 | for direction in range(3): 195 | if edge(vl[positiveBlockEdges[direction][0][0]],vl[positiveBlockEdges[direction][0][1]]) in edgeSet: 196 | if not edgeDirections[es]: 197 | edgeDirections[es] = set([(vl[e[0]],vl[e[1]]) for e in positiveBlockEdges[direction]]) 198 | else: 199 | simedges = edgeDirections[es].intersection([(vl[e[0]],vl[e[1]]) for e in positiveBlockEdges[direction]]) 200 | if simedges: 201 | edgeDirections[es] |= set([(vl[e[0]],vl[e[1]]) for e in positiveBlockEdges[direction]]) 202 | else: 203 | asimedges= set(edgeDirections[es]).intersection([(vl[e[1]],vl[e[0]]) for e in positiveBlockEdges[direction]]) 204 | if asimedges: 205 | edgeDirections[es] |= set([(vl[e[1]],vl[e[0]]) for e in positiveBlockEdges[direction]]) 206 | 207 | return edgeDirections 208 | 209 | def sortEdges(edges): 210 | sorted=[] 211 | # Find out if the edges form a loop 212 | edges1D=np.ravel(edges) 213 | occ=np.bincount(edges1D) 214 | # This is a loop, let's just start sorting anywhere (from first element here) 215 | if len(np.where(occ==1)[0])==0: 216 | sorted.append(edges[0][0]) 217 | # This is not a loop, let's find the first or last element 218 | else: 219 | # Find a vertex which occurs only 1 and then it's place in 2D list 220 | firstidx1D=np.where(edges1D==np.where(occ==1)[0][0])[0][0] 221 | if firstidx1D % 2 == 0: 222 | sorted.append(edges[int(firstidx1D/2)][0]) 223 | else: 224 | sorted.append(edges[int((firstidx1D-1)/2)][1]) 225 | edgesTemp = [] 226 | vertids = [] 227 | for e in edges: 228 | vertids.append(e[0]) 229 | vertids.append(e[1]) 230 | vertids = list(set(vertids)) 231 | vertid=sorted[0] 232 | edgesTemp=edges[:] 233 | for i in range(len(vertids)): 234 | for eid, e in enumerate(edgesTemp): 235 | if vertid in e: 236 | if e[0] == vertid: 237 | sorted.append(e[1]) 238 | else: 239 | sorted.append(e[0]) 240 | edgesTemp.pop(eid) 241 | vertid = sorted[-1] 242 | break 243 | return sorted 244 | 245 | def obFromStructuredMesh(verts, dim, objName): 246 | context = bpy.context 247 | nx, ny, nz = dim 248 | edges = [] 249 | faces = [] 250 | boundary_verts = [] 251 | boundary_mes = [] 252 | boundary_verts.append(list(verts[0:nx*ny])) 253 | boundary_verts.append(verts[nx*ny*nz-nx*ny:]) 254 | boundary_verts.append(verts[::nx]) 255 | boundary_verts.append(verts[nx-1::nx]) 256 | boundary_verts.append([]) 257 | 258 | for sverts in range(0,nx*ny*nz,nx*ny): 259 | boundary_verts[-1].extend(verts[sverts:sverts+nx]) 260 | 261 | boundary_verts.append([]) 262 | for sverts in range(nx*ny-nx,nx*ny*nz,nx*ny): 263 | boundary_verts[-1].extend(verts[sverts:sverts+nx]) 264 | 265 | verts = [v for bv in boundary_verts for v in bv] 266 | boundary_faces = [] 267 | boundary_ij = [[nx,ny], [ny,nz], [nx,nz]] 268 | vert_idx = 0 269 | # With Numpy slicing? 270 | for ni, nj in boundary_ij: 271 | bf = [] 272 | for j in range(nj-1): 273 | for i in range(ni-1): 274 | bf.append((i+j*ni,1+i+j*ni,1+i+(1+j)*ni,i+(1+j)*ni)) 275 | 276 | boundary_faces.append(bf) 277 | boundary_faces.append(bf) 278 | # Blender face arrays do not work with np.ints 279 | faces.extend((np.array(bf)+vert_idx).tolist()) 280 | vert_idx += ni*nj 281 | 282 | faces.extend((np.array(bf)+vert_idx).tolist()) 283 | vert_idx += ni*nj 284 | 285 | 286 | boundary_mes = [bpy.data.meshes.new('boundary_%s'%i) for i in range(6)] 287 | for bm, bv, bf in zip(boundary_mes, boundary_verts, boundary_faces): 288 | bm.from_pydata(bv, [], bf) 289 | 290 | vol_me=bpy.data.meshes.new('internal') 291 | vol_me.from_pydata(verts, edges,faces) 292 | vol_me.update() 293 | 294 | ob = bpy.data.objects.new(objName,vol_me) 295 | context.scene.objects.link(ob) 296 | boundary_obs = [] 297 | for i, bm in enumerate(boundary_mes): 298 | boundary_ob = bpy.data.objects.new(objName+ '_{}'.format(i), bm) 299 | boundary_ob.parent = ob 300 | # boundary_ob.show_all_edges = True 301 | # boundary_ob.show_wire = True 302 | context.scene.objects.link(boundary_ob) 303 | boundary_obs.append(boundary_ob) 304 | return ob 305 | 306 | 307 | def getBlockFaces(verts): 308 | fids = [(0,1,5,4),(0,3,2,1),(3,7,6,2),(4,5,6,7),(0,4,7,3),(1,2,6,5)] 309 | faces = [(verts[f[0]],verts[f[1]],verts[f[2]],verts[f[3]]) for f in fids] 310 | return faces 311 | 312 | 313 | 314 | --------------------------------------------------------------------------------