├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── doc └── image │ ├── copySymmetricUvs.png │ ├── triplanarUnwrap.png │ ├── uvBrush.png │ └── uvPlanarProjection.png ├── make.py ├── makeDeploy.py ├── source ├── __init__.py ├── icons │ ├── icons.psd │ ├── uvBrush.png │ └── uvPlaneTool.png └── operators │ ├── blenderUtil.py │ ├── copySymmetricUvs.py │ ├── facesToGrid.py │ ├── handles.py │ ├── triplanarUvUnwrap.py │ ├── uvBrushTool.py │ ├── uvLayoutPlane.py │ ├── uvToolsPanel.py │ └── vecmath.py └── test ├── bar.blend ├── numpyTest.blend ├── plane.blend ├── suzanne.blend └── triangle.blend /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: markmckay 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: kitfox_com 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | #custom: paypal.me/kitfoxArtAndCode -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /test/*.blend1 3 | /deploy 4 | /__pycache__ 5 | -------------------------------------------------------------------------------- /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 | # UV Tool Suite for Blender 2 | 3 | A set of tools to make editing UVs easier in Blender. 4 | 5 | These tools can be accessed wither through the **Kitfox - UV** panel on the right of the 3D Viewport. You can also access them from the uv unwrap menu (press U while in edit mode). 6 | 7 | [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/donate?hosted_button_id=2FMMA3S9WVGL4) 8 | 9 | ### UV Brush 10 | 11 | ![UV Brush](doc/image/uvBrush.png) 12 | 13 | Adjust the UVs on your mesh by stroking your model with a brush. 14 | 15 | 16 | #### UV Brush 17 | Start the UV Brush tool. 18 | 19 | #### Radius 20 | Radius of brush stroke. You can also press the **[** and **]** keys to change the radius of the brush. 21 | 22 | #### Strength 23 | Multiplier for the strength of your brush stroke. 24 | 25 | #### Pen Pressure 26 | If checked, the pressure you apply with your stylus will multiply the strength of your brush. 27 | 28 | 29 | 30 | 31 | ### UV Plane Projection 32 | 33 | ![UV Plane Projection](doc/image/uvPlanarProjection.png) 34 | 35 | Creates a control that allows you to perform a UV planar projection in the viewport. 36 | 37 | Click and drag handles to resize, translate or rotate the control. Hold **shift** when dragging scale handles for uniform scaling. Hold **control** when rotating to snap rotations to increments of 15 degrees. 38 | 39 | 40 | #### UV Plane Project 41 | Start the plane project tool. 42 | 43 | #### Selected Faces Only 44 | If checked, only faces selected on your mesh will be affected by the control. 45 | 46 | #### Step by UVs 47 | If checked, when dragging the translation handles of the control, the UV adjustment will be snapped to multiples of the **Step UV Scalar**. 48 | 49 | #### Step UV Scalar 50 | When **Step by UVs** is enabled, specifies the snapping distance in UV space. 51 | 52 | 53 | #### Start Mode 54 | Defines how the control should be initialized when the **Uv Plane Project** button is pressed. 55 | 56 | - **Bounds** - Control aligns to the bounding box of your mesh. 57 | - **Face** - Control will attempt to match the existing UVs of the active face. 58 | - **Grid** - Control will match a single grid square. 59 | 60 | #### Relocate Origin 61 | When in **Face** mode, origin of UVs will be recalculated to be near center of the active face. 62 | 63 | 64 | 65 | 66 | ### Copy Symmetric UVs 67 | 68 | ![Copy Symmetric UVs](doc/image/copySymmetricUvs.png) 69 | 70 | Copy UVs to faces that are reflected across an axis. For every selected face, this tool will check if a mirror image exists of it on the other side of the axis. If so, the UVs of the selected side are copied to the unselected side. If both are selected, the positive side of the axis is copied to the negative side. 71 | 72 | #### Axis 73 | Axis to reflect UVs across. 74 | 75 | #### Epsilon 76 | How close vertices need to be to be considered overlapping. The reflected face's vertices must be within this tolerance of the source face's vertices. 77 | 78 | 79 | 80 | 81 | ### Triplanar Projection 82 | 83 | ![Triplanar Unwrap](doc/image/triplanarUnwrap.png) 84 | 85 | Perform a cubemap projection based on the grid coordinates. 86 | 87 | #### Use Grid Scale 88 | If true, the current scale factor of the grid will be applied to the projection. Otherwise the layout will be done with absolute values. 89 | 90 | #### Uniform Scale 91 | If true, u and v axes will be scaled uniformly. Otherwise scaling for each axis can be specified separately. 92 | 93 | #### U Scale 94 | Multiplier for U coordinate. 95 | 96 | #### V Scale 97 | Multiplier for V coordinate. 98 | 99 | 100 | ### Correct Face Attributes 101 | 102 | This is the same attribute that Blender provides under the Tool/Options/Correct Face Attributes when in Edit mode. It is duplicated here for convenience. 103 | 104 | 105 | 106 | 107 | ## Building 108 | 109 | To build, execute the *makeDeploy.py* script in the root of the project. It will create a directory called *deploy* that contains a zip file containing the addon. 110 | 111 | ## Installation 112 | 113 | To install, start Blender and select Edit > Preferences from the menubar. Select the Add-ons tab and then press the Install button. Browse to the .zip file that you built and select it. Finally, tick the checkbox next to Add Mesh: Normal Brush. 114 | 115 | ## Further Information 116 | 117 | This addon is available from the Blender market: 118 | 119 | https://blendermarket.com/products/uv-tools 120 | 121 | 122 | A video giving a quick tour of the addon is available here: 123 | 124 | [![Video thumbnail](https://img.youtube.com/vi/bnz31KJJITc/0.jpg)](https://youtu.be/bnz31KJJITc) 125 | [![Video thumbnail](https://img.youtube.com/vi/hsBdzfSci8k/0.jpg)](https://youtu.be/hsBdzfSci8k) 126 | 127 | -------------------------------------------------------------------------------- /doc/image/copySymmetricUvs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/doc/image/copySymmetricUvs.png -------------------------------------------------------------------------------- /doc/image/triplanarUnwrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/doc/image/triplanarUnwrap.png -------------------------------------------------------------------------------- /doc/image/uvBrush.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/doc/image/uvBrush.png -------------------------------------------------------------------------------- /doc/image/uvPlanarProjection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/doc/image/uvPlanarProjection.png -------------------------------------------------------------------------------- /make.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderEasyFly). 4 | # Copyright (c) 2021 Mark McKay 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, version 3. 9 | # 10 | # This program is distributed in the hope that it will be useful, but 11 | # WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | # General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | import os 19 | import shutil 20 | import sys 21 | import getopt 22 | import platform 23 | 24 | def copytree(src, dst): 25 | for item in os.listdir(src): 26 | 27 | s = os.path.join(src, item) 28 | d = os.path.join(dst, item) 29 | if os.path.isdir(s): 30 | os.mkdir(d) 31 | copytree(s, d) 32 | else: 33 | filename, extn = os.path.splitext(item) 34 | print ("file " + filename + " extn " + extn) 35 | if (extn != ".py" and extn != ".png"): 36 | continue 37 | 38 | shutil.copy(s, d) 39 | 40 | def make(copyToBlenderAddons = False, createArchive = False): 41 | projectName = 'uvTools' 42 | 43 | blenderHome = None 44 | # platSys = platform.system() 45 | # if platSys == 'Windows': 46 | # appData = os.getenv('APPDATA') 47 | # blenderHome = os.path.join(appData, "Blender Foundation/Blender/2.92") 48 | 49 | # elif platSys == 'Linux': 50 | # home = os.getenv('HOME') 51 | # blenderHome = os.path.join(home, ".config/blender/2.92/") 52 | 53 | 54 | blenderHome = os.getenv('BLENDER_HOME') 55 | 56 | #Create build directory 57 | curPath = os.getcwd() 58 | if os.path.exists('build'): 59 | shutil.rmtree('build') 60 | os.mkdir('build') 61 | os.mkdir('build/' + projectName) 62 | 63 | copytree("source", "build/" + projectName); 64 | 65 | 66 | #Build addon zip file 67 | if createArchive: 68 | if os.path.exists('deploy'): 69 | shutil.rmtree('deploy') 70 | os.mkdir('deploy') 71 | 72 | shutil.make_archive("deploy/" + projectName, "zip", "build") 73 | 74 | 75 | if copyToBlenderAddons: 76 | if blenderHome == None: 77 | print("Error: BLENDER_HOME not set. Files not copied to /script/addons.") 78 | return 79 | 80 | addonPath = os.path.join(blenderHome, "scripts/addons") 81 | destPath = os.path.join(addonPath, projectName) 82 | 83 | print("Copying to blender addons: " + addonPath) 84 | if os.path.exists(destPath): 85 | shutil.rmtree(destPath) 86 | copytree("build", addonPath); 87 | 88 | 89 | if __name__ == '__main__': 90 | copyToBlenderAddons = False 91 | createArchive = False 92 | 93 | for arg in sys.argv[1:]: 94 | if arg == "-a": 95 | createArchive = True 96 | if arg == "-b": 97 | copyToBlenderAddons = True 98 | 99 | make(copyToBlenderAddons, createArchive) 100 | 101 | -------------------------------------------------------------------------------- /makeDeploy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import make 4 | 5 | make.make(createArchive = True) 6 | 7 | -------------------------------------------------------------------------------- /source/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | 17 | bl_info = { 18 | "name": "Uv Tools", 19 | "description": "Tools for editing UVs in the viewport.", 20 | "author": "Mark McKay", 21 | "version": (1, 0, 9), 22 | "blender": (4, 0, 0), 23 | "location": "View3D", 24 | # "wiki_url": "https://github.com/blackears/uvTools", 25 | # "tracker_url": "https://github.com/blackears/uvTools", 26 | "category": "View 3D" 27 | } 28 | 29 | import bpy 30 | import importlib 31 | 32 | 33 | if "bpy" in locals(): 34 | if "uvBrushTool" in locals(): 35 | importlib.reload(uvBrushTool) 36 | else: 37 | from .operators import uvBrushTool 38 | 39 | if "uvLayoutPlane" in locals(): 40 | importlib.reload(uvLayoutPlane) 41 | else: 42 | from .operators import uvLayoutPlane 43 | 44 | if "triplanarUvUnwrap" in locals(): 45 | importlib.reload(triplanarUvUnwrap) 46 | else: 47 | from .operators import triplanarUvUnwrap 48 | 49 | if "copySymmetricUvs" in locals(): 50 | importlib.reload(copySymmetricUvs) 51 | else: 52 | from .operators import copySymmetricUvs 53 | 54 | if "facesToGrid" in locals(): 55 | importlib.reload(facesToGrid) 56 | else: 57 | from .operators import facesToGrid 58 | 59 | if "uvToolsPanel" in locals(): 60 | importlib.reload(uvToolsPanel) 61 | else: 62 | from .operators import uvToolsPanel 63 | 64 | else: 65 | from .operators import uvBrushTool 66 | from .operators import triplanarUvUnwrap 67 | from .operators import copySymmetricUvs 68 | from .operators import uvLayoutPlane 69 | from .operators import uvToolsPanel 70 | from .operators import facesToGrid 71 | 72 | def register(): 73 | uvBrushTool.register() 74 | triplanarUvUnwrap.register() 75 | copySymmetricUvs.register() 76 | uvLayoutPlane.register() 77 | facesToGrid.register() 78 | uvToolsPanel.register() 79 | 80 | 81 | def unregister(): 82 | uvBrushTool.unregister() 83 | triplanarUvUnwrap.unregister() 84 | copySymmetricUvs.unregister() 85 | uvLayoutPlane.unregister() 86 | facesToGrid.unregister() 87 | uvToolsPanel.unregister() 88 | 89 | -------------------------------------------------------------------------------- /source/icons/icons.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/source/icons/icons.psd -------------------------------------------------------------------------------- /source/icons/uvBrush.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/source/icons/uvBrush.png -------------------------------------------------------------------------------- /source/icons/uvPlaneTool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/source/icons/uvPlaneTool.png -------------------------------------------------------------------------------- /source/operators/blenderUtil.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import mathutils 18 | 19 | def redraw_all_viewports(context): 20 | for area in bpy.context.screen.areas: # iterate through areas in current screen 21 | if area.type == 'VIEW_3D': 22 | area.tag_redraw() 23 | 24 | #Wrap Blender's ray_cast, since the way the method was called changed in verison 2.91 25 | def ray_cast_scene(context, viewlayer, ray_origin, view_vector): 26 | if bpy.app.version >= (2, 91, 0): 27 | return context.scene.ray_cast(viewlayer.depsgraph, ray_origin, view_vector) 28 | else: 29 | return context.scene.ray_cast(viewlayer, ray_origin, view_vector) 30 | 31 | 32 | def mesh_bounds_world(obj): 33 | 34 | minCo = None 35 | maxCo = None 36 | mesh = obj.data 37 | 38 | for v in mesh.vertices: 39 | pos = mathutils.Vector(v.co) 40 | pos = obj.matrix_world @ pos 41 | 42 | # print("pos " + str(pos)) 43 | 44 | if minCo == None: 45 | minCo = mathutils.Vector(pos) 46 | maxCo = mathutils.Vector(pos) 47 | else: 48 | minCo.x = min(minCo.x, pos.x) 49 | minCo.y = min(minCo.y, pos.y) 50 | minCo.z = min(minCo.z, pos.z) 51 | maxCo.x = max(maxCo.x, pos.x) 52 | maxCo.y = max(maxCo.y, pos.y) 53 | maxCo.z = max(maxCo.z, pos.z) 54 | 55 | return (minCo, maxCo) 56 | -------------------------------------------------------------------------------- /source/operators/copySymmetricUvs.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import bmesh 18 | import mathutils 19 | import math 20 | 21 | 22 | #-------------------------------------- 23 | 24 | class CopySymmetricUvSettings(bpy.types.PropertyGroup): 25 | axis : bpy.props.EnumProperty( 26 | items=( 27 | ('X', "X Axis", "Copy to faces across X axis"), 28 | ('Y', "Y Axis", "Copy to faces across Y axis"), 29 | ('Z', "Z Axis", "Copy to faces across Z axis") 30 | ), 31 | default='X' 32 | ) 33 | 34 | epsilon : bpy.props.FloatProperty( 35 | name="Epsilon", description="How far away vertices can be and still be considered overlapping.", default = .001, min=0, soft_max = .01 36 | ) 37 | 38 | different_islands_only : bpy.props.BoolProperty( 39 | name="Different Islands Only", description="Only copy the face if it belongs to a different uv island than the current face.", default = True 40 | ) 41 | 42 | 43 | #-------------------------------------- 44 | 45 | class CopySymmetricUvsOperator(bpy.types.Operator): 46 | """Copy UVs to faces that are symmetrically opposite of selected faces""" 47 | bl_idname = "kitfox.copy_symmetric_uvs" 48 | bl_label = "Copy Symmetric UVs" 49 | bl_options = {"REGISTER", "UNDO"} 50 | 51 | def __init__(self, *args, **kwargs): 52 | super().__init__(*args, **kwargs) 53 | pass 54 | 55 | 56 | def __del__(self): 57 | super().__del__() 58 | 59 | def findLoopMap(self, f0, f1, xform, epsilon): 60 | #Compare vertex positions 61 | if len(f0.loops) != len(f1.loops): 62 | return None 63 | 64 | indices = [] 65 | 66 | for loop0 in f0.loops: 67 | pos0 = xform @ loop0.vert.co 68 | foundMatch = False 69 | 70 | 71 | for loop1 in f1.loops: 72 | pos1 = loop1.vert.co 73 | 74 | dist = pos0 - pos1 75 | if dist.magnitude < epsilon: 76 | foundMatch = True 77 | break 78 | 79 | if not foundMatch: 80 | return None 81 | 82 | indices.append(loop1) 83 | 84 | return indices 85 | 86 | 87 | def execute(self, context): 88 | props = context.scene.kitfox_copy_symmetric_uvs 89 | epsilon = props.epsilon 90 | axis = props.axis 91 | 92 | 93 | 94 | if axis == 'X': 95 | mMirror = mathutils.Matrix.Diagonal((-1, 1, 1)) 96 | axisVec = mathutils.Vector((1, 0, 0)) 97 | elif axis == 'Y': 98 | mMirror = mathutils.Matrix.Diagonal((1, -1, 1)) 99 | axisVec = mathutils.Vector((0, 1, 0)) 100 | elif axis == 'Z': 101 | mMirror = mathutils.Matrix.Diagonal((1, 1, -1)) 102 | axisVec = mathutils.Vector((0, 0, 1)) 103 | 104 | for obj in context.selected_objects: 105 | if obj.type != "MESH": 106 | continue 107 | 108 | l2w = obj.matrix_world 109 | 110 | mesh = obj.data 111 | 112 | if obj.mode == 'EDIT': 113 | bm = bmesh.from_edit_mesh(mesh) 114 | elif obj.mode == 'OBJECT': 115 | bm = bmesh.new() 116 | bm.from_mesh(mesh) 117 | 118 | uv_layer = bm.loops.layers.uv.verify() 119 | 120 | selectedFaces = [] 121 | 122 | for f in bm.faces: 123 | if f.select: 124 | selectedFaces.append(f) 125 | 126 | for f0 in selectedFaces: 127 | for f1 in bm.faces: 128 | if f0 == f1.loops: 129 | continue 130 | 131 | center0 = f0.calc_center_bounds() 132 | center1 = f1.calc_center_bounds() 133 | 134 | center1m = mMirror @ center1 135 | 136 | if (center0 - center1m).magnitude > epsilon: 137 | continue 138 | 139 | if f1.select: 140 | if axisVec.dot(center1) > 0: 141 | #If both source face and reflection are selected, copy from positive side of axis to negative 142 | continue 143 | 144 | loopMap = self.findLoopMap(f0, f1, mMirror, epsilon) 145 | if loopMap == None: 146 | continue 147 | 148 | #Copy uv 149 | for i in range(len(loopMap)): 150 | loop0 = f0.loops[i] 151 | loop1 = loopMap[i] 152 | loop1[uv_layer].uv = loop0[uv_layer].uv 153 | 154 | 155 | if obj.mode == 'EDIT': 156 | bmesh.update_edit_mesh(mesh) 157 | elif obj.mode == 'OBJECT': 158 | bm.to_mesh(mesh) 159 | bm.free() 160 | 161 | 162 | 163 | return {'FINISHED'} 164 | 165 | #--------------------------- 166 | 167 | 168 | def register(): 169 | bpy.utils.register_class(CopySymmetricUvSettings) 170 | bpy.utils.register_class(CopySymmetricUvsOperator) 171 | 172 | bpy.types.Scene.kitfox_copy_symmetric_uvs = bpy.props.PointerProperty(type=CopySymmetricUvSettings) 173 | 174 | 175 | def unregister(): 176 | 177 | bpy.utils.unregister_class(CopySymmetricUvSettings) 178 | bpy.utils.unregister_class(CopySymmetricUvsOperator) 179 | 180 | del bpy.types.Scene.kitfox_copy_symmetric_uvs 181 | 182 | 183 | if __name__ == "__main__": 184 | register() 185 | 186 | 187 | -------------------------------------------------------------------------------- /source/operators/facesToGrid.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import bmesh 18 | import math 19 | from enum import Enum 20 | from mathutils import * 21 | 22 | class FaceUvsToGridProperties(bpy.types.PropertyGroup): 23 | 24 | grid_cells_x : bpy.props.IntProperty( 25 | name="Grid U", 26 | description="Number of cells wide UV grid is along U axis.", 27 | default = 1, 28 | min=0, 29 | soft_max = 4 30 | ) 31 | 32 | grid_cells_y : bpy.props.IntProperty( 33 | name="Grid V", 34 | description="Number of cells wide UV grid is along U axis.", 35 | default = 1, 36 | min=0, 37 | soft_max = 4 38 | ) 39 | 40 | winding : bpy.props.EnumProperty( 41 | items=( 42 | ('KEEP', "Keep", "Keep current winding."), 43 | ('CW', "CW", "UVs travel clockwise around face."), 44 | ('CCW', "CCW", "UVs travel counter-clockwise around face."), 45 | ), 46 | default='KEEP' 47 | ) 48 | 49 | uv_align_direction : bpy.props.FloatVectorProperty( 50 | name="Align Direction", 51 | description="Direction used by Align UVs.", 52 | default = (0, 0, 1), 53 | subtype='DIRECTION' 54 | ) 55 | 56 | 57 | class ShiftType(Enum): 58 | REVERSE = 1 59 | CW = 2 60 | CCW = 3 61 | 62 | def redraw_all_viewports(context): 63 | for area in bpy.context.screen.areas: # iterate through areas in current screen 64 | if area.type == 'VIEW_3D': 65 | area.tag_redraw() 66 | 67 | 68 | 69 | def align_face_uvs(context): 70 | props = context.scene.faces_to_grid_props 71 | uv_align_direction = props.uv_align_direction.to_3d() 72 | 73 | for obj in context.selected_objects: 74 | if obj.type != 'MESH': 75 | continue 76 | 77 | 78 | mesh = obj.data 79 | if obj.mode == 'EDIT': 80 | bm = bmesh.from_edit_mesh(mesh) 81 | elif obj.mode == 'OBJECT': 82 | bm = bmesh.new() 83 | bm.from_mesh(mesh) 84 | 85 | uv_layer = bm.loops.layers.uv.verify() 86 | 87 | # adjust uv coordinates 88 | for face in bm.faces: 89 | if face.select: 90 | # print("---face") 91 | uvs = [] 92 | weights = [] 93 | 94 | num_uvs = len(face.loops) 95 | for i in range(num_uvs): 96 | loop = face.loops[i] 97 | uvs.append(loop[uv_layer].uv.copy()) 98 | weights.append(uv_align_direction.dot(loop.vert.co)) 99 | 100 | #Find best weighted sum of Vs for all possible sequences of uvs 101 | best_offset = -1 102 | best_offset_sum = 0 103 | for offset in range(num_uvs): 104 | sum = 0 105 | for i in range(num_uvs): 106 | sum += uvs[(i + offset) % num_uvs].y * weights[i] 107 | 108 | # print("offset " + str(offset) + " sum " + str(sum)) 109 | 110 | if best_offset == -1 or sum > best_offset_sum: 111 | best_offset = offset 112 | best_offset_sum = sum 113 | 114 | # print("best_offset " + str(best_offset) + " best_sum " + str(best_offset_sum)) 115 | 116 | for i in range(num_uvs): 117 | loop = face.loops[i] 118 | loop[uv_layer].uv = uvs[(i + best_offset) % num_uvs] 119 | 120 | 121 | if obj.mode == 'EDIT': 122 | bmesh.update_edit_mesh(mesh) 123 | elif obj.mode == 'OBJECT': 124 | bm.to_mesh(mesh) 125 | bm.free() 126 | 127 | redraw_all_viewports(context) 128 | 129 | def shift_face_uvs(context, shift_type): 130 | props = context.scene.faces_to_grid_props 131 | grid_cells_x = props.grid_cells_x 132 | grid_cells_y = props.grid_cells_y 133 | winding = props.winding 134 | 135 | for obj in context.selected_objects: 136 | if obj.type != 'MESH': 137 | continue 138 | 139 | 140 | mesh = obj.data 141 | if obj.mode == 'EDIT': 142 | bm = bmesh.from_edit_mesh(mesh) 143 | elif obj.mode == 'OBJECT': 144 | bm = bmesh.new() 145 | bm.from_mesh(mesh) 146 | 147 | 148 | uv_layer = bm.loops.layers.uv.verify() 149 | 150 | # adjust uv coordinates 151 | for face in bm.faces: 152 | if face.select: 153 | uvs = [] 154 | num_uvs = len(face.loops) 155 | for i in range(num_uvs): 156 | loop = face.loops[i] 157 | uvs.append(loop[uv_layer].uv.copy()) 158 | 159 | for i in range(num_uvs): 160 | loop = face.loops[i] 161 | if shift_type == ShiftType.CW: 162 | iNext = i + 1 if i < num_uvs - 1 else 0 163 | elif shift_type == ShiftType.CCW: 164 | iNext = i - 1 if i > 0 else num_uvs - 1 165 | else: 166 | iNext = num_uvs - 1 - i 167 | 168 | loop[uv_layer].uv = uvs[iNext] 169 | 170 | 171 | if obj.mode == 'EDIT': 172 | bmesh.update_edit_mesh(mesh) 173 | elif obj.mode == 'OBJECT': 174 | bm.to_mesh(mesh) 175 | bm.free() 176 | 177 | redraw_all_viewports(context) 178 | 179 | #------------------------------------- 180 | 181 | class RotUvsCwOperator(bpy.types.Operator): 182 | """Rotate face UVs clockwise.""" 183 | bl_idname = "kitfox.rot_uvs_cw" 184 | bl_label = "Rotate Uvs Clockwise" 185 | bl_options = {'REGISTER', 'UNDO'} 186 | 187 | @classmethod 188 | def poll(cls, context): 189 | obj = context.active_object 190 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 191 | 192 | 193 | def execute(self, context): 194 | shift_face_uvs(context, ShiftType.CW) 195 | return {'FINISHED'} 196 | 197 | #------------------------------------- 198 | 199 | class RotUvsCcwOperator(bpy.types.Operator): 200 | """Rotate face UVs counter-clockwise.""" 201 | bl_idname = "kitfox.rot_uvs_ccw" 202 | bl_label = "Rotate Uvs Clockwise" 203 | bl_options = {'REGISTER', 'UNDO'} 204 | 205 | @classmethod 206 | def poll(cls, context): 207 | obj = context.active_object 208 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 209 | 210 | 211 | def execute(self, context): 212 | shift_face_uvs(context, ShiftType.CCW) 213 | return {'FINISHED'} 214 | 215 | #------------------------------------- 216 | 217 | class ReverseFaceUvsOperator(bpy.types.Operator): 218 | """Reverse winding of face UVs.""" 219 | bl_idname = "kitfox.reverse_face_uvs" 220 | bl_label = "Reverse Face UVs" 221 | bl_options = {'REGISTER', 'UNDO'} 222 | 223 | @classmethod 224 | def poll(cls, context): 225 | obj = context.active_object 226 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 227 | 228 | 229 | def execute(self, context): 230 | shift_face_uvs(context, ShiftType.REVERSE) 231 | return {'FINISHED'} 232 | 233 | #------------------------------------- 234 | 235 | class CopyFaceUvsOperator(bpy.types.Operator): 236 | """Set UVs of selected faces to match that of the active face.""" 237 | bl_idname = "kitfox.copy_face_uvs_unwrap" 238 | bl_label = "Copy Face Uvs" 239 | bl_options = {'REGISTER', 'UNDO'} 240 | 241 | 242 | @classmethod 243 | def poll(cls, context): 244 | obj = context.active_object 245 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 246 | # return obj and obj.type == 'MESH' and obj.mode == 'OBJECT' 247 | 248 | 249 | def execute(self, context): 250 | props = context.scene.faces_to_grid_props 251 | grid_cells_x = props.grid_cells_x 252 | grid_cells_y = props.grid_cells_y 253 | winding = props.winding 254 | 255 | # print("faceToGrid exec") 256 | 257 | for obj in context.selected_objects: 258 | if obj.type != 'MESH': 259 | continue 260 | 261 | 262 | mesh = obj.data 263 | if obj.mode == 'EDIT': 264 | bm = bmesh.from_edit_mesh(mesh) 265 | elif obj.mode == 'OBJECT': 266 | bm = bmesh.new() 267 | bm.from_mesh(mesh) 268 | 269 | 270 | uv_layer = bm.loops.layers.uv.verify() 271 | 272 | # print("obj " + obj.name) 273 | 274 | active = bm.faces.active 275 | if active == None: 276 | continue 277 | 278 | 279 | # adjust uv coordinates 280 | for face in bm.faces: 281 | if face.select and face != active: 282 | 283 | for i in range(len(face.loops)): 284 | loop = face.loops[i] 285 | activeI = i if i < len(active.loops) else len(active.loops) - 1 286 | 287 | loop[uv_layer].uv = active.loops[activeI][uv_layer].uv.copy() 288 | 289 | 290 | if obj.mode == 'EDIT': 291 | bmesh.update_edit_mesh(mesh) 292 | elif obj.mode == 'OBJECT': 293 | bm.to_mesh(mesh) 294 | bm.free() 295 | 296 | redraw_all_viewports(context) 297 | 298 | return {'FINISHED'} 299 | 300 | 301 | #------------------------------------- 302 | 303 | class AlignFaceUvsOperator(bpy.types.Operator): 304 | """Rotate UVs so that their V axis is pointing along the Align Direction as much as is possible.""" 305 | bl_idname = "kitfox.align_face_uvs" 306 | bl_label = "Align Face UVs" 307 | bl_options = {'REGISTER', 'UNDO'} 308 | 309 | @classmethod 310 | def poll(cls, context): 311 | obj = context.active_object 312 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 313 | 314 | def execute(self, context): 315 | align_face_uvs(context) 316 | return {'FINISHED'} 317 | 318 | #------------------------------------- 319 | 320 | 321 | class FaceUvsToGridOperator(bpy.types.Operator): 322 | """Set UVs per face so that they fit a grid square.""" 323 | bl_idname = "kitfox.face_uvs_to_grid_unwrap" 324 | bl_label = "Face Uvs to Grid" 325 | bl_options = {'REGISTER', 'UNDO'} 326 | 327 | 328 | @classmethod 329 | def poll(cls, context): 330 | obj = context.active_object 331 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 332 | # return obj and obj.type == 'MESH' and obj.mode == 'OBJECT' 333 | 334 | def execute(self, context): 335 | props = context.scene.faces_to_grid_props 336 | grid_cells_x = props.grid_cells_x 337 | grid_cells_y = props.grid_cells_y 338 | winding = props.winding 339 | 340 | # print("--faceToGrid exec") 341 | 342 | for obj in context.selected_objects: 343 | if obj.type != 'MESH': 344 | continue 345 | 346 | 347 | mesh = obj.data 348 | if obj.mode == 'EDIT': 349 | bm = bmesh.from_edit_mesh(mesh) 350 | elif obj.mode == 'OBJECT': 351 | bm = bmesh.new() 352 | bm.from_mesh(mesh) 353 | 354 | uv_layer = bm.loops.layers.uv.verify() 355 | 356 | # print("obj " + obj.name) 357 | 358 | # adjust uv coordinates 359 | for face in bm.faces: 360 | if face.select: 361 | 362 | uvCenter = None 363 | 364 | for loop in face.loops: 365 | if uvCenter == None: 366 | uvCenter = Vector(loop[uv_layer].uv) 367 | else: 368 | uvCenter += Vector(loop[uv_layer].uv) 369 | 370 | if uvCenter == None: 371 | uvCenter = Vector((0, 0)) 372 | 373 | uvCenter *= 1.0 / len(face.loops) 374 | 375 | # print ("Uv center " + str(uvCenter)) 376 | 377 | cell_x = int((uvCenter.x - math.floor(uvCenter.x)) * grid_cells_x) 378 | cell_y = int((uvCenter.y - math.floor(uvCenter.y)) * grid_cells_y) 379 | 380 | # print ("cell_x " + str(cell_x)) 381 | # print ("cell_y " + str(cell_y)) 382 | 383 | # print ("face.loops[0][uv_layer].uv " + str(face.loops[0][uv_layer].uv)) 384 | 385 | uvDir = face.loops[0][uv_layer].uv - uvCenter 386 | uvDirSign = Vector((-1 if uvDir.x < 0 else 1, -1 if uvDir.y < 0 else 1)) 387 | 388 | # print ("uvDir " + str(uvDir)) 389 | # print ("uvDirSign " + str(uvDirSign)) 390 | 391 | area = 0 392 | for i in range(len(face.loops)): 393 | loop0 = face.loops[i] 394 | loop1 = face.loops[0 if i == len(face.loops) - 1 else i + 1] 395 | 396 | uv0 = loop0[uv_layer].uv 397 | uv1 = loop1[uv_layer].uv 398 | area += uv0.x * uv1.y - uv0.y * uv1.x 399 | 400 | 401 | mT = Matrix.Translation((1, 1, 0)) 402 | mS = Matrix.Diagonal((1.0 / (grid_cells_x * 2), 1.0 / (grid_cells_y * 2), 1, 1)) 403 | mT2 = Matrix.Translation((cell_x / grid_cells_x, cell_y / grid_cells_y, 0)) 404 | mUvXlate = mT2 @ mS @ mT 405 | 406 | for i in range(len(face.loops)): 407 | uvPos = mUvXlate @ uvDirSign.to_4d() 408 | # print ("- uvDirSign " + str(uvDirSign)) 409 | # print ("- uvPos " + str(uvPos)) 410 | 411 | face.loops[i][uv_layer].uv = uvPos.to_2d() 412 | 413 | ccw = (winding == 'KEEP' and area >= 0) or winding == 'CCW' 414 | if ccw: 415 | #CCW 416 | tmp = uvDirSign.y 417 | uvDirSign.y = uvDirSign.x 418 | uvDirSign.x = -tmp 419 | else: 420 | tmp = uvDirSign.x 421 | uvDirSign.x = uvDirSign.y 422 | uvDirSign.y = -tmp 423 | 424 | 425 | 426 | if obj.mode == 'EDIT': 427 | bmesh.update_edit_mesh(mesh) 428 | elif obj.mode == 'OBJECT': 429 | bm.to_mesh(mesh) 430 | bm.free() 431 | 432 | redraw_all_viewports(context) 433 | 434 | return {'FINISHED'} 435 | 436 | 437 | #------------------------------------- 438 | 439 | 440 | 441 | class FaceUvsToGridPanel(bpy.types.Panel): 442 | 443 | """Properties Panel for Trim Sheet Tools""" 444 | bl_label = "Trim Sheet Tools" 445 | bl_idname = "OBJECT_PT_kitfox_face_uvs_to_grid" 446 | bl_space_type = 'VIEW_3D' 447 | bl_region_type = 'UI' 448 | bl_category = "Kitfox - UV" 449 | 450 | 451 | 452 | @classmethod 453 | def poll(cls, context): 454 | obj = context.object 455 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 456 | 457 | def draw(self, context): 458 | layout = self.layout 459 | 460 | scene = context.scene 461 | settings = scene.uv_brush_props 462 | 463 | #-------------------------------- 464 | 465 | props = context.scene.faces_to_grid_props 466 | 467 | col = layout.column(); 468 | col.operator("kitfox.face_uvs_to_grid_unwrap") 469 | 470 | col.prop(props, "grid_cells_x") 471 | col.prop(props, "grid_cells_y") 472 | col.prop(props, "winding", text = "Winding") 473 | 474 | col.operator("kitfox.copy_face_uvs_unwrap") 475 | col.operator("kitfox.rot_uvs_cw", text="Rotate CW") 476 | col.operator("kitfox.rot_uvs_ccw", text="Rotate CCW") 477 | col.operator("kitfox.reverse_face_uvs", text="Reverse Face Winding") 478 | col.operator("kitfox.align_face_uvs", text="Align UVs") 479 | 480 | col.prop(props, "uv_align_direction", expand = True) 481 | 482 | #------------------------------------- 483 | 484 | 485 | def menu_start_faceUvsToGrid(self, context): 486 | self.layout.operator_context = 'INVOKE_DEFAULT' 487 | self.layout.operator("kitfox.uv_brush_operator") 488 | 489 | 490 | def register(): 491 | bpy.utils.register_class(FaceUvsToGridProperties) 492 | bpy.utils.register_class(FaceUvsToGridOperator) 493 | bpy.utils.register_class(CopyFaceUvsOperator) 494 | bpy.utils.register_class(RotUvsCwOperator) 495 | bpy.utils.register_class(RotUvsCcwOperator) 496 | bpy.utils.register_class(ReverseFaceUvsOperator) 497 | bpy.utils.register_class(AlignFaceUvsOperator) 498 | 499 | bpy.utils.register_class(FaceUvsToGridPanel) 500 | 501 | 502 | bpy.types.VIEW3D_MT_uv_map.prepend(menu_start_faceUvsToGrid) 503 | 504 | bpy.types.Scene.faces_to_grid_props = bpy.props.PointerProperty(type=FaceUvsToGridProperties) 505 | 506 | 507 | def unregister(): 508 | bpy.utils.unregister_class(FaceUvsToGridProperties) 509 | bpy.utils.unregister_class(FaceUvsToGridOperator) 510 | bpy.utils.unregister_class(CopyFaceUvsOperator) 511 | bpy.utils.unregister_class(RotUvsCwOperator) 512 | bpy.utils.unregister_class(RotUvsCcwOperator) 513 | bpy.utils.unregister_class(ReverseFaceUvsOperator) 514 | bpy.utils.unregister_class(AlignFaceUvsOperator) 515 | bpy.utils.unregister_class(FaceUvsToGridPanel) 516 | bpy.types.VIEW3D_MT_uv_map.remove(menu_start_faceUvsToGrid) 517 | 518 | del bpy.types.Scene.faces_to_grid_props 519 | 520 | 521 | if __name__ == "__main__": 522 | register() 523 | 524 | 525 | 526 | -------------------------------------------------------------------------------- /source/operators/handles.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import mathutils 18 | import math 19 | import gpu 20 | import bgl 21 | 22 | from gpu_extras.batch import batch_for_shader 23 | from bpy_extras import view3d_utils 24 | 25 | from .vecmath import * 26 | 27 | #--------------------------- 28 | 29 | class HandleContraint: 30 | def __init__(self): 31 | pass 32 | 33 | def constrain(self, offset, viewDir): 34 | #By default just pass back offset 35 | return offset 36 | 37 | class HandleConstraintVector(HandleContraint): 38 | def __init__(self, vector): 39 | super().__init__() 40 | self.vector = vector 41 | 42 | def constrain(self, offset, viewDir): 43 | # print("---Constrain ") 44 | # print("vector " + str(self.vector)) 45 | # print("offset " + str(offset)) 46 | # print("viewDir " + str(viewDir)) 47 | scalar = closest_point_to_line(vecZero, self.vector, offset, viewDir) 48 | # print("scalar " + str(scalar)) 49 | # print("scalar * self.vector " + str(scalar * self.vector)) 50 | # print("---") 51 | return scalar * self.vector 52 | 53 | # return offset.project(self.vector) 54 | 55 | class HandleConstraintPlane(HandleContraint): 56 | def __init__(self, planeOrigin, planeNormal): 57 | super().__init__() 58 | self.planeOrigin = planeOrigin 59 | self.planeNormal = planeNormal 60 | 61 | def constrain(self, offset, viewDir): 62 | s = isect_line_plane(offset, viewDir, self.planeOrigin, self.planeNormal) 63 | return offset + s * viewDir 64 | 65 | def copy(self): 66 | return HandleConstraintPlane(self.planeOrigin.copy(), self.planeNormal.copy()) 67 | 68 | 69 | class HandleConstraintOmni(HandleContraint): 70 | def __init__(self): 71 | super().__init__() 72 | 73 | def constrain(self, offset, viewDir): 74 | return offset 75 | 76 | 77 | #--------------------------- 78 | 79 | 80 | class HandleBody: 81 | def __init__(self, handle, transform, color, colorDrag): 82 | self.handle = handle 83 | self.transform = transform 84 | self.color = color 85 | self.colorDrag = colorDrag 86 | self.dragging = False 87 | self.viewportScale = 500 88 | 89 | def setColor(self, color): 90 | self.color = color 91 | 92 | def draw(self, context, dragging): 93 | 94 | #Replace scaling component from handle transform 95 | trans, rot, scale = self.handle.transform.decompose() 96 | 97 | region = context.region 98 | rv3d = context.region_data 99 | #unitScale = calc_unit_scale2(trans, region, rv3d) 100 | unitScale = dist_from_viewport_center3(trans, region, rv3d) 101 | fract = self.viewportScale / region.height 102 | viewport_scale = fract / unitScale 103 | # viewport_scale = self.viewportScale / unitScale 104 | mS = mathutils.Matrix.Diagonal((viewport_scale, viewport_scale, viewport_scale, 1)) 105 | 106 | hM = mathutils.Matrix.Translation(trans) @ rot.to_matrix().to_4x4() @ mS 107 | l2w = hM @ self.transform 108 | 109 | 110 | # bgl.glEnable(bgl.GL_DEPTH_TEST) 111 | 112 | gpu.matrix.push() 113 | 114 | gpu.matrix.multiply_matrix(l2w) 115 | 116 | 117 | if dragging: 118 | self.shader.uniform_float("color", self.colorDrag) 119 | else: 120 | self.shader.uniform_float("color", self.color) 121 | self.batchShape.draw(self.shader) 122 | 123 | gpu.matrix.pop() 124 | 125 | # bgl.glDisable(bgl.GL_DEPTH_TEST) 126 | 127 | 128 | def intersect(self, context, pickOrigin, pickRay): 129 | 130 | trans, rot, scale = self.handle.transform.decompose() 131 | 132 | region = context.region 133 | rv3d = context.region_data 134 | # unitScale = dist_from_viewport_center(trans, region, rv3d) 135 | # unitScale = 1 / unitScale 136 | # print("unitScale " + str(unitScale)) 137 | # viewport_scale = self.viewportScale / unitScale 138 | unitScale = dist_from_viewport_center3(trans, region, rv3d) 139 | fract = self.viewportScale / region.height 140 | viewport_scale = fract / unitScale 141 | 142 | mS = mathutils.Matrix.Diagonal((viewport_scale, viewport_scale, viewport_scale, 1)) 143 | 144 | # print("view Mtx " + str(rv3d.view_matrix)) 145 | # print("window Mtx " + str(rv3d.window_matrix)) 146 | # print("perspective_matrix " + str(rv3d.perspective_matrix)) 147 | 148 | 149 | hM = mathutils.Matrix.Translation(trans) @ rot.to_matrix().to_4x4() @ mS 150 | l2w = hM @ self.transform 151 | 152 | for i in range(len(self.coords) // 3): 153 | p0 = self.coords[i * 3] 154 | p1 = self.coords[i * 3 + 1] 155 | p2 = self.coords[i * 3 + 2] 156 | 157 | p0w = l2w @ p0 158 | p1w = l2w @ p1 159 | p2w = l2w @ p2 160 | 161 | hit = intersect_triangle(p0w, p1w, p2w, pickOrigin, pickRay) 162 | if hit != None: 163 | # print("hit p0:%s p1:%s p2:%s " % (str(p0w), str(p1w), str(p2w))) 164 | # print("hit pickOrigin:%s pickRay:%s" % (str(pickOrigin), str(pickRay))) 165 | 166 | return hit 167 | 168 | return None 169 | 170 | 171 | class HandleBodyCube(HandleBody): 172 | def __init__(self, handle, transform, color, colorDrag): 173 | super().__init__(handle, transform, color, colorDrag) 174 | 175 | self.coords, normals, uvs = unitCube() 176 | 177 | self.shader = gpu.shader.from_builtin('UNIFORM_COLOR') 178 | self.batchShape = batch_for_shader(self.shader, 'TRIS', {"pos": self.coords}) 179 | 180 | 181 | 182 | class HandleBodySphere(HandleBody): 183 | def __init__(self, handle, transform, color, colorDrag): 184 | super().__init__(handle, transform, color, colorDrag) 185 | 186 | self.coords, normals, uvs = unitSphere() 187 | 188 | self.shader = gpu.shader.from_builtin('UNIFORM_COLOR') 189 | self.batchShape = batch_for_shader(self.shader, 'TRIS', {"pos": self.coords}) 190 | 191 | 192 | class HandleBodyCone(HandleBody): 193 | def __init__(self, handle, transform, color, colorDrag): 194 | super().__init__(handle, transform, color, colorDrag) 195 | 196 | self.coords, normals, uvs = unitCone(cap = True) 197 | 198 | self.shader = gpu.shader.from_builtin('UNIFORM_COLOR') 199 | self.batchShape = batch_for_shader(self.shader, 'TRIS', {"pos": self.coords}) 200 | 201 | 202 | class HandleBodyTorus(HandleBody): 203 | def __init__(self, handle, transform, color, colorDrag): 204 | super().__init__(handle, transform, color, colorDrag) 205 | 206 | self.coords, normals, uvs = unitTorus(radius = 8, ring_radius = .3) 207 | 208 | self.shader = gpu.shader.from_builtin('UNIFORM_COLOR') 209 | self.batchShape = batch_for_shader(self.shader, 'TRIS', {"pos": self.coords}) 210 | 211 | 212 | #--------------------------- 213 | 214 | 215 | class Handle: 216 | def __init__(self, transform, body, constraint): 217 | #Location in world space 218 | self.transform = transform 219 | self.body = body 220 | self.constraint = constraint 221 | 222 | self.dragging = False 223 | 224 | def draw(self, context): 225 | 226 | self.body.draw(context, self.dragging) 227 | 228 | 229 | 230 | class HandleScaleAroundPivot(Handle): 231 | #posControl is position within uv square that this control point represents 232 | def __init__(self, control, transform, pivot, constraint, posControl): 233 | 234 | self.pivot = pivot 235 | self.control = control 236 | xform = mathutils.Matrix.Diagonal(mathutils.Vector((.02, .02, .02, 1))) 237 | body = HandleBodyCube(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 238 | 239 | #Location of handle in i, j, k coords of control's projection matrix 240 | self.posControl = posControl 241 | 242 | super().__init__(transform, body, constraint) 243 | 244 | 245 | def mouse_click(self, context, event): 246 | if event.value == "PRESS": 247 | if not self.dragging: 248 | region = context.region 249 | rv3d = context.region_data 250 | 251 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 252 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 253 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 254 | 255 | hit = self.body.intersect(context, mouse_near_origin, mouse_ray) 256 | if hit != None: 257 | self.dragging = True 258 | self.drag_start_pos = hit 259 | 260 | #Structure of original projection matrix 261 | self.startControlProj = self.control.controlMtx.copy() 262 | 263 | # print("--starting drag") 264 | # print("startControlProj %s" % (str(self.startControlProj))) 265 | 266 | return True 267 | 268 | else: 269 | if self.dragging: 270 | self.dragging = False 271 | # self.drag_offset = None 272 | 273 | #self.mesh_tracker.stretch(self.move_amount, self.dir, self.face, True) 274 | return True 275 | 276 | return False 277 | 278 | def mouse_move(self, context, event): 279 | if self.dragging: 280 | region = context.region 281 | rv3d = context.region_data 282 | 283 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 284 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 285 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 286 | 287 | #calc offset in 3d space perpendicular to view direction 288 | startPointOffset = self.drag_start_pos - mouse_near_origin 289 | offsetPerpendicularToViewDir = startPointOffset.project(mouse_ray) - startPointOffset 290 | 291 | # print("posControl %s" % (str(self.posControl))) 292 | # print("offsetPerpendicularToViewDir %s" % (str(offsetPerpendicularToViewDir))) 293 | 294 | offset = self.constraint.constrain(offsetPerpendicularToViewDir, mouse_ray) 295 | 296 | pos2Uv = self.startControlProj.inverted() 297 | offsetUv = mult_vector(pos2Uv, offset) 298 | # tmp = offset.to_4d() 299 | # tmp.w = 0 300 | # offsetUv = pos2Uv @ tmp 301 | # offsetUv = offsetUv.to_3d() 302 | 303 | # print("offsetUv %s" % (str(offsetUv))) 304 | 305 | 306 | fixedPosUv = self.pivot * 2 - self.posControl 307 | spanNewUv = self.posControl + offsetUv - fixedPosUv 308 | spanUv = self.posControl - fixedPosUv 309 | 310 | if event.shift: 311 | spanNewUv = spanNewUv.project(spanUv) 312 | 313 | 314 | # print("fixedPosUv %s" % (str(fixedPosUv))) 315 | # print("spanUv %s" % (str(spanUv))) 316 | # print("spanNewUv %s" % (str(spanNewUv))) 317 | 318 | sx = 1 if spanUv.x == 0 else spanNewUv.x / spanUv.x 319 | sy = 1 if spanUv.y == 0 else spanNewUv.y / spanUv.y 320 | 321 | #This is the transform in UV space that moves the starting uv point to its new position 322 | T = mathutils.Matrix.Translation((fixedPosUv)) @ mathutils.Matrix.Diagonal((sx, sy, 1, 1)) @ mathutils.Matrix.Translation((-fixedPosUv)) 323 | 324 | # print("T %s" % (str(T))) 325 | 326 | newProjMatrix = self.startControlProj @ T 327 | 328 | self.control.updateProjectionMatrix(context, newProjMatrix) 329 | 330 | return True 331 | return False 332 | 333 | 334 | class HandleCorner(HandleScaleAroundPivot): 335 | def __init__(self, control, transform, normal, posControl): 336 | 337 | constraint = HandleConstraintPlane(vecZero, normal) 338 | 339 | super().__init__(control, transform, mathutils.Vector((.5, .5, 0)), constraint, posControl) 340 | 341 | 342 | class HandleEdge(HandleScaleAroundPivot): 343 | def __init__(self, control, transform, direction, posControl): 344 | 345 | constraint = HandleConstraintVector(direction) 346 | 347 | super().__init__(control, transform, mathutils.Vector((.5, .5, 0)), constraint, posControl) 348 | 349 | 350 | class HandleTranslate(Handle): 351 | def __init__(self, control, transform, body, constraint, posControl): 352 | 353 | self.control = control 354 | # xform = mathutils.Matrix.Diagonal(mathutils.Vector((.02, .02, .02, 1))) 355 | # body = HandleBodyCone(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 356 | # body = HandleBodySphere(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 357 | # body = HandleBodyCube(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 358 | 359 | #Location of handle in i, j, k coords of control's projection matrix 360 | self.posControl = posControl 361 | 362 | super().__init__(transform, body, constraint) 363 | 364 | 365 | def mouse_click(self, context, event): 366 | if event.value == "PRESS": 367 | if not self.dragging: 368 | region = context.region 369 | rv3d = context.region_data 370 | 371 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 372 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 373 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 374 | 375 | hit = self.body.intersect(context, mouse_near_origin, mouse_ray) 376 | if hit != None: 377 | self.dragging = True 378 | self.drag_start_pos = hit 379 | 380 | #Structure of original projection matrix 381 | self.startControlProj = self.control.controlMtx.copy() 382 | 383 | return True 384 | else: 385 | if self.dragging: 386 | self.dragging = False 387 | return True 388 | 389 | return False 390 | 391 | def mouse_move(self, context, event): 392 | if self.dragging: 393 | 394 | props = context.scene.kitfox_uv_plane_layout_props 395 | clamp_to_basis = props.clamp_to_basis 396 | clamp_scalar = props.clamp_scalar 397 | 398 | region = context.region 399 | rv3d = context.region_data 400 | 401 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 402 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 403 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 404 | 405 | #calc offset in 3d space perpendicular to view direction 406 | startPointOffset = self.drag_start_pos - mouse_near_origin 407 | offsetPerpendicularToViewDir = startPointOffset.project(mouse_ray) - startPointOffset 408 | 409 | # print("posControl %s" % (str(self.posControl))) 410 | # print("offsetPerpToView %s" % (str(offsetPerpToView))) 411 | 412 | offset = self.constraint.constrain(offsetPerpendicularToViewDir, mouse_ray) 413 | 414 | # print("offset %s" % (str(offset))) 415 | 416 | if clamp_to_basis: 417 | uv2w = self.startControlProj 418 | w2uv = uv2w.inverted() 419 | 420 | off = offset.to_4d() 421 | off.w = 0 422 | uvOff = w2uv @ off 423 | uvOff /= clamp_scalar 424 | 425 | uvOff.x = math.floor(uvOff.x) 426 | uvOff.y = math.floor(uvOff.y) 427 | uvOff.z = math.floor(uvOff.z) 428 | 429 | uvOff *= clamp_scalar 430 | offset = uv2w @ uvOff 431 | offset = offset.to_3d() 432 | 433 | 434 | 435 | newProjMatrix = mathutils.Matrix.Translation(offset) @ self.startControlProj 436 | 437 | #print("newProjMatrix %s" % (str(newProjMatrix))) 438 | 439 | self.control.updateProjectionMatrix(context, newProjMatrix) 440 | 441 | return True 442 | return False 443 | 444 | 445 | class HandleTranslateOmni(HandleTranslate): 446 | def __init__(self, control, transform, posControl): 447 | xform = mathutils.Matrix.Diagonal(mathutils.Vector((.04, .04, .04, 1))) 448 | body = HandleBodySphere(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 449 | 450 | super().__init__(control, transform, body, HandleConstraintOmni(), posControl) 451 | 452 | 453 | class HandleTranslateVector(HandleTranslate): 454 | def __init__(self, control, transform, constraintVector, posControl): 455 | xform = mathutils.Matrix.Diagonal(mathutils.Vector((.04, .04, .04, 1))) 456 | 457 | #Rotate body to point along vector 458 | axis = constraintVector.cross(vecZ) 459 | if axis.magnitude > 0: 460 | i = constraintVector.normalized() 461 | angle = math.acos(i.z) 462 | q = mathutils.Quaternion(axis, angle) 463 | mR = q.to_matrix().to_4x4() 464 | 465 | xform = mR @ xform 466 | elif constraintVector.dot(vecZ) > 0: 467 | mR = mathutils.Matrix.Rotation(math.pi, 4, vecX) 468 | 469 | xform = mR @ xform 470 | 471 | body = HandleBodyCone(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 472 | 473 | super().__init__(control, transform, body, HandleConstraintVector(constraintVector), posControl) 474 | 475 | 476 | class HandleRotateAxis(Handle): 477 | def __init__(self, control, transform, axis, axisLocal): 478 | 479 | # constraint = HandleConstraintPlane(axis) 480 | 481 | self.pivot = mathutils.Vector((.5, .5, 0)) 482 | pivotWorld = control.controlMtx @ self.pivot 483 | constraint = HandleConstraintPlane(pivotWorld, axis) 484 | 485 | self.axisLocal = axisLocal 486 | self.control = control 487 | xform = mathutils.Matrix.Diagonal(mathutils.Vector((.03, .03, .03, 1))) 488 | body = HandleBodyTorus(self, xform, (1, 0, 1, 1), (1, 1, 0, 1)) 489 | # body.viewportScale = 300 490 | 491 | super().__init__(transform, body, constraint) 492 | 493 | def draw(self, context): 494 | super().draw(context) 495 | 496 | # gpu.matrix.push() 497 | # gpu.matrix.multiply_matrix(self.transform) 498 | 499 | # self.body.draw(context, self.dragging) 500 | 501 | # gpu.matrix.pop() 502 | 503 | def mouse_click(self, context, event): 504 | if event.value == "PRESS": 505 | if not self.dragging: 506 | region = context.region 507 | rv3d = context.region_data 508 | 509 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 510 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 511 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 512 | 513 | hit = self.body.intersect(context, mouse_near_origin, mouse_ray) 514 | if hit != None: 515 | self.dragging = True 516 | self.drag_start_pos = hit 517 | self.start_constraint = self.constraint.copy() 518 | 519 | #Structure of original projection matrix 520 | self.startControlProj = self.control.controlMtx.copy() 521 | 522 | return True 523 | else: 524 | if self.dragging: 525 | self.dragging = False 526 | return True 527 | 528 | return False 529 | 530 | def mouse_move(self, context, event): 531 | if self.dragging: 532 | region = context.region 533 | rv3d = context.region_data 534 | 535 | mouse_pos_2d = (event.mouse_region_x, event.mouse_region_y) 536 | mouse_ray = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos_2d) 537 | mouse_near_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos_2d) 538 | 539 | #calc offset in 3d space perpendicular to view direction 540 | startPointOffset = self.drag_start_pos - mouse_near_origin 541 | offsetPerpendicularToViewDir = startPointOffset.project(mouse_ray) - startPointOffset 542 | 543 | print("self.drag_start_pos %s" % (str(self.drag_start_pos))) 544 | 545 | # print("posControl %s" % (str(self.posControl))) 546 | # print("offsetPerpToView %s" % (str(offsetPerpToView))) 547 | p0 = self.drag_start_pos 548 | p1 = self.drag_start_pos + offsetPerpendicularToViewDir 549 | 550 | print("p0 %s" % (str(p0))) 551 | print("p1 %s" % (str(p1))) 552 | 553 | p0 = self.start_constraint.constrain(p0, mouse_ray) 554 | p1 = self.start_constraint.constrain(p1, mouse_ray) 555 | 556 | print("p0 const %s" % (str(p0))) 557 | print("p1 const %s" % (str(p1))) 558 | 559 | # offset = self.constraint.constrain(offsetPerpToView, mouse_ray) 560 | 561 | # print("offset %s" % (str(offset))) 562 | 563 | origin = self.startControlProj @ self.pivot 564 | 565 | print("origin %s" % (str(origin))) 566 | 567 | # v0 = self.drag_start_pos - origin 568 | # v1 = (self.drag_start_pos + offset) - origin 569 | v0 = p0 - origin 570 | v1 = p1 - origin 571 | 572 | # print("v0 %s" % (str(v0))) 573 | # print("v1 %s" % (str(v1))) 574 | 575 | v0.normalize() 576 | v1.normalize() 577 | 578 | 579 | 580 | # print("v0 norm %s" % (str(v0))) 581 | # print("v1 norm %s" % (str(v1))) 582 | 583 | clamped_dot = min(1.0, max(-1.0, v0.dot(v1))) 584 | angle = math.acos(clamped_dot) 585 | vc = v0.cross(v1) 586 | 587 | # print("vc %s" % (str(vc))) 588 | 589 | #Find angle relative to normal of axis 590 | axisWorld = self.start_constraint.planeNormal 591 | if vc.dot(axisWorld) < 0: 592 | angle = -angle 593 | 594 | # print("angle %s" % (str(angle * 180 / math.pi))) 595 | 596 | if event.ctrl: 597 | # print ("snapping angle " + str(math.degrees(angle))) 598 | snapAngle = (15 / 360) * (2 * math.pi) 599 | angle = math.floor(angle / snapAngle) * snapAngle 600 | # print ("snapping after angle " + str(math.degrees(angle))) 601 | 602 | mRot = mathutils.Matrix.Rotation(angle, 4, axisWorld) 603 | 604 | pivotPos = self.startControlProj @ self.pivot 605 | mPivot = mathutils.Matrix.Translation(pivotPos) 606 | mPivotNeg = mathutils.Matrix.Translation(-pivotPos) 607 | 608 | trans, rot, scale = self.startControlProj.decompose() 609 | newProjMatrix = mPivot @ mRot @ mPivotNeg @ self.startControlProj 610 | 611 | # print("newProjMatrix %s" % (str(newProjMatrix))) 612 | 613 | self.control.updateProjectionMatrix(context, newProjMatrix) 614 | 615 | return True 616 | return False 617 | -------------------------------------------------------------------------------- /source/operators/triplanarUvUnwrap.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import bmesh 18 | import mathutils 19 | 20 | 21 | class TriplanarSettings(bpy.types.PropertyGroup): 22 | 23 | scale_uniform : bpy.props.BoolProperty( 24 | name="Scale Uniform", description="If true, both axes will be scaled by the same amount. Otherwise u and v scaling can be specified separately.", default = True 25 | ) 26 | 27 | scale_u : bpy.props.FloatProperty( 28 | name="U Scale", description="Scale of texture along horizon", default = 1, min=0, soft_max = 4 29 | ) 30 | 31 | scale_v : bpy.props.FloatProperty( 32 | name="V Scale", description="Scale of texture along vertical", default = 1, min=0, soft_max = 4 33 | ) 34 | 35 | use_grid_scale : bpy.props.BoolProperty( 36 | name="Use Grid Scale", description="If true, multiply coords by current grid size.", default = False 37 | ) 38 | 39 | def redraw_all_viewports(context): 40 | for area in bpy.context.screen.areas: # iterate through areas in current screen 41 | if area.type == 'VIEW_3D': 42 | area.tag_redraw() 43 | 44 | def map_editmode(context): 45 | settings = context.scene.triplanar_settings_props 46 | 47 | scale = context.space_data.overlay.grid_scale 48 | use_grid_scale = settings.use_grid_scale 49 | print("scale %s" % (str(scale))) 50 | print("use_grid_scale %s" % (str(use_grid_scale))) 51 | 52 | for obj in context.selected_objects: 53 | if obj.type != 'MESH': 54 | continue 55 | 56 | l2w = obj.matrix_world 57 | 58 | me = obj.data 59 | bm = bmesh.from_edit_mesh(me) 60 | # bm = bmesh.new() 61 | # bm.from_mesh(me) 62 | 63 | uv_layer = bm.loops.layers.uv.verify() 64 | 65 | 66 | # adjust uv coordinates 67 | for face in bm.faces: 68 | if face.select: 69 | xAbs = abs(face.normal.x) 70 | yAbs = abs(face.normal.y) 71 | zAbs = abs(face.normal.z) 72 | 73 | for loop in face.loops: 74 | loop_uv = loop[uv_layer] 75 | 76 | wco = l2w @ loop.vert.co 77 | 78 | # use xy position of the vertex as a uv coordinate 79 | uv = None 80 | if (xAbs > yAbs and xAbs > zAbs): 81 | uv = mathutils.Vector(wco.yz) 82 | elif (yAbs > zAbs): 83 | uv = mathutils.Vector(wco.xz) 84 | else: 85 | uv = mathutils.Vector(wco.xy) 86 | 87 | if settings.scale_uniform: 88 | uv.x /= settings.scale_u 89 | uv.y /= settings.scale_u 90 | else: 91 | uv.x /= settings.scale_u 92 | uv.y /= settings.scale_v 93 | 94 | if use_grid_scale: 95 | uv /= scale 96 | 97 | loop_uv.uv = uv 98 | 99 | bmesh.update_edit_mesh(me) 100 | # bm.to_mesh(me) 101 | # bm.free() 102 | 103 | redraw_all_viewports(context) 104 | 105 | 106 | def map_objectmode(context): 107 | settings = context.scene.triplanar_settings_props 108 | scale = context.space_data.overlay.grid_scale 109 | use_grid_scale = settings.use_grid_scale 110 | print("scale %s" % (str(scale))) 111 | print("use_grid_scale %s" % (str(use_grid_scale))) 112 | 113 | for obj in context.selected_objects: 114 | if obj.type != 'MESH': 115 | continue 116 | 117 | l2w = obj.matrix_world 118 | 119 | me = obj.data 120 | # bm = bmesh.from_edit_mesh(me) 121 | bm = bmesh.new() 122 | bm.from_mesh(me) 123 | 124 | uv_layer = bm.loops.layers.uv.verify() 125 | 126 | 127 | # adjust uv coordinates 128 | for face in bm.faces: 129 | xAbs = abs(face.normal.x) 130 | yAbs = abs(face.normal.y) 131 | zAbs = abs(face.normal.z) 132 | 133 | for loop in face.loops: 134 | loop_uv = loop[uv_layer] 135 | 136 | wco = l2w @ loop.vert.co 137 | 138 | # use xy position of the vertex as a uv coordinate 139 | uv = None 140 | if (xAbs > yAbs and xAbs > zAbs): 141 | uv = mathutils.Vector(wco.yz) 142 | elif (yAbs > zAbs): 143 | uv = mathutils.Vector(wco.xz) 144 | else: 145 | uv = mathutils.Vector(wco.xy) 146 | 147 | if settings.scale_uniform: 148 | uv.x /= settings.scale_u 149 | uv.y /= settings.scale_u 150 | else: 151 | uv.x /= settings.scale_u 152 | uv.y /= settings.scale_v 153 | 154 | if use_grid_scale: 155 | uv /= scale 156 | 157 | loop_uv.uv = uv 158 | 159 | # bmesh.update_edit_mesh(me) 160 | bm.to_mesh(me) 161 | bm.free() 162 | 163 | redraw_all_viewports(context) 164 | 165 | 166 | class TriplanarUvUnwrapOperator(bpy.types.Operator): 167 | """Perform cubemap projection using grid coodinates to generate uvs.""" 168 | bl_idname = "kitfox.triplanar_uv_unwrap" 169 | bl_label = "Triplanar Unwrap" 170 | bl_options = {'REGISTER', 'UNDO'} 171 | 172 | # scale: FloatProperty( 173 | # name="Scale", 174 | # description="Scale UVs by this", 175 | # soft_min=0.1, soft_max=10.0, 176 | # default=0.5, 177 | # ) 178 | 179 | @classmethod 180 | def poll(cls, context): 181 | obj = context.active_object 182 | return obj and obj.type == 'MESH' and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 183 | # return obj and obj.type == 'MESH' and obj.mode == 'OBJECT' 184 | 185 | def execute(self, context): 186 | obj = context.active_object 187 | if obj.mode == 'EDIT': 188 | map_editmode(context) 189 | elif obj.mode == 'OBJECT': 190 | map_objectmode(context) 191 | return {'FINISHED'} 192 | 193 | 194 | # def menu_func(self, context): 195 | # self.layout.operator("kitfox.triplanar_uv_unwrap") 196 | # # bl_idname should be in form of "something.something" 197 | # # or YourClass.bl_idname 198 | 199 | 200 | def register(): 201 | bpy.utils.register_class(TriplanarSettings) 202 | bpy.utils.register_class(TriplanarUvUnwrapOperator) 203 | # bpy.types.VIEW3D_MT_uv_map.prepend(menu_func) 204 | 205 | bpy.types.Scene.triplanar_settings_props = bpy.props.PointerProperty(type=TriplanarSettings) 206 | 207 | 208 | def unregister(): 209 | bpy.utils.unregister_class(TriplanarSettings) 210 | bpy.utils.unregister_class(TriplanarUvUnwrapOperator) 211 | # bpy.types.VIEW3D_MT_uv_map.remove(menu_func) 212 | 213 | del bpy.types.Scene.triplanar_settings_props 214 | 215 | 216 | if __name__ == "__main__": 217 | register() -------------------------------------------------------------------------------- /source/operators/uvBrushTool.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import bpy.utils.previews 18 | import os 19 | #import bgl 20 | import blf 21 | import gpu 22 | import mathutils 23 | import math 24 | import bmesh 25 | from .vecmath import * 26 | from .blenderUtil import * 27 | 28 | from gpu_extras.batch import batch_for_shader 29 | from bpy_extras import view3d_utils 30 | 31 | 32 | #preview_collections = {} 33 | 34 | 35 | circleSegs = 64 36 | coordsCircle = [(math.sin(((2 * math.pi * i) / circleSegs)), math.cos((math.pi * 2 * i) / circleSegs), 0) for i in range(circleSegs + 1)] 37 | 38 | coordsNormal = [(0, 0, 0), (0, 0, 1)] 39 | 40 | vecZ = mathutils.Vector((0, 0, 1)) 41 | vecX = mathutils.Vector((1, 0, 0)) 42 | 43 | shader = gpu.shader.from_builtin('UNIFORM_COLOR') 44 | batchLine = batch_for_shader(shader, 'LINES', {"pos": coordsNormal}) 45 | batchCircle = batch_for_shader(shader, 'LINE_STRIP', {"pos": coordsCircle}) 46 | 47 | #-------------------------------------- 48 | 49 | class UvBrushToolSettings(bpy.types.PropertyGroup): 50 | 51 | radius : bpy.props.FloatProperty( 52 | name="Radius", description="Radius of brush", default = 1, min=0, soft_max = 4 53 | ) 54 | 55 | strength : bpy.props.FloatProperty( 56 | name="Strength", description="Strength of brush", default = 1, min=0, soft_max = 4 57 | ) 58 | 59 | use_pressure : bpy.props.BoolProperty( 60 | name="Pen Pressure", description="If true, pen pressure is used to adjust strength", default = False 61 | ) 62 | 63 | #-------------------------------------- 64 | 65 | 66 | #Find matrix that maps onto vertex UV space with Z along normal 67 | #coord - point in world space 68 | #normal - normal in world space 69 | def calc_vertex_transform_world(pos, norm): 70 | axis = norm.cross(vecZ) 71 | if axis.length_squared < .0001: 72 | axis = mathutils.Vector(vecX) 73 | else: 74 | axis.normalize() 75 | angle = -math.acos(norm.dot(vecZ)) 76 | 77 | quat = mathutils.Quaternion(axis, angle) 78 | mR = quat.to_matrix() 79 | mR.resize_4x4() 80 | 81 | mT = mathutils.Matrix.Translation(pos) 82 | 83 | m = mT @ mR 84 | return m 85 | 86 | 87 | def draw_callback(self, context): 88 | # if True: 89 | # return 90 | 91 | ctx = bpy.context 92 | 93 | region = context.region 94 | rv3d = context.region_data 95 | 96 | viewport_center = (region.x + region.width / 2, region.y + region.height / 2) 97 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, viewport_center) 98 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, viewport_center) 99 | 100 | 101 | shader.bind(); 102 | 103 | #bgl.glEnable(bgl.GL_DEPTH_TEST) 104 | 105 | #Draw cursor 106 | if self.show_cursor: 107 | brush_radius = context.scene.uv_brush_props.radius 108 | 109 | m = calc_vertex_transform_world(self.cursor_pos, self.cursor_normal); 110 | mS = mathutils.Matrix.Scale(brush_radius, 4) 111 | m = m @ mS 112 | 113 | #Tangent to mesh 114 | gpu.matrix.push() 115 | 116 | gpu.matrix.multiply_matrix(m) 117 | 118 | shader.uniform_float("color", (1, 0, 1, 1)) 119 | batchCircle.draw(shader) 120 | 121 | gpu.matrix.pop() 122 | 123 | 124 | #bgl.glDisable(bgl.GL_DEPTH_TEST) 125 | 126 | class UvTracker: 127 | def __init__(self, uv, dist, newUv): 128 | self.uv = uv 129 | self.dist = dist 130 | self.newUv = newUv 131 | 132 | def toString(self): 133 | print(" uv %s dist %s newUv %s" % (str(self.uv), str(self.dist), str(self.newUv))) 134 | 135 | class VertexTracker: 136 | 137 | def __init__(self, vert): 138 | self.vert = vert 139 | self.uvInfo = [] 140 | 141 | def considerUv(self, uv_in, dist_in, newUv_in): 142 | # print("Adding uv %s dist %s newUv %s" % (str(uv_in), str(dist_in), str(newUv_in))) 143 | 144 | for i in range(len(self.uvInfo)): 145 | map = self.uvInfo[i] 146 | 147 | #Check if uv_in already has an entry for this vertex 148 | if map.uv == uv_in: 149 | # print("found in map") 150 | if map.dist > dist_in: 151 | # print("adding to map") 152 | map.dist = dist_in 153 | map.newUv = newUv_in 154 | 155 | return 156 | 157 | #Uv for this vertex not encountered yet. Create new entry 158 | map = UvTracker(uv_in, dist_in, newUv_in) 159 | self.uvInfo.append(map) 160 | 161 | def getNewUv(self, uv): 162 | # print("Looking up uv %s " % (str(uv))) 163 | for map in self.uvInfo: 164 | # print("Checking against uv %s " % (str(map.uv))) 165 | if map.uv == uv: 166 | # print("Matched!") 167 | return map.newUv 168 | 169 | return None 170 | 171 | def toString(self): 172 | print(" vert_index %d" % (self.vert_index)) 173 | for map in self.uvInfo: 174 | map.toString() 175 | 176 | 177 | #------------------------------------- 178 | 179 | class UvBrushToolOperator(bpy.types.Operator): 180 | """Move uvs on your mesh by stroking a brush.""" 181 | bl_idname = "kitfox.uv_brush_operator" 182 | bl_label = "UV Brush" 183 | bl_options = {"REGISTER", "UNDO"} 184 | 185 | def __init__(self, *args, **kwargs): 186 | super().__init__(*args, **kwargs) 187 | self.dragging = False 188 | 189 | self.cursor_pos = None 190 | self.show_cursor = False 191 | self.edit_object = None 192 | self.stroke_trail = [] 193 | 194 | self.history = [] 195 | self.history_idx = -1 196 | self.history_limit = 10 197 | self.history_bookmarks = {} 198 | 199 | # print("construct UvBrushToolOperator") 200 | 201 | def __del__(self): 202 | super().__del__() 203 | 204 | def free_snapshot(self, map): 205 | for obj in map: 206 | bm = map[obj] 207 | bm.free() 208 | 209 | #if bookmark is other than -1, snapshot added to bookmark library rather than undo stack 210 | def history_snapshot(self, context, bookmark = -1): 211 | if True: 212 | #Disabling history for now 213 | return 214 | 215 | map = {} 216 | for obj in context.selected_objects: 217 | if obj.type == 'MESH': 218 | bm = bmesh.new() 219 | 220 | mesh = obj.data 221 | bm.from_mesh(mesh) 222 | map[obj] = bm 223 | 224 | if bookmark != -1: 225 | self.history_bookmarks[bookmark] = map 226 | 227 | else: 228 | #Remove first element if history queue is maxed out 229 | if self.history_idx == self.history_limit: 230 | self.free_snapshot(self.history[0]) 231 | self.history.pop(0) 232 | 233 | self.history_idx += 1 234 | 235 | #Remove all history past current pointer 236 | while self.history_idx < len(self.history) - 1: 237 | self.free_snapshot(self.history[-1]) 238 | self.history.pop() 239 | 240 | self.history.append(map) 241 | self.history_idx += 1 242 | 243 | def history_undo(self, context): 244 | if True: 245 | #Disabling history for now 246 | return 247 | 248 | if (self.history_idx == 0): 249 | return 250 | 251 | self.history_undo_to_snapshot(context, self.history_idx - 1) 252 | 253 | def history_redo(self, context): 254 | if True: 255 | #Disabling history for now 256 | return 257 | 258 | if (self.history_idx == len(self.history) - 1): 259 | return 260 | 261 | self.history_undo_to_snapshot(context, self.history_idx + 1) 262 | 263 | 264 | def history_restore_bookmark(self, context, bookmark): 265 | if True: 266 | #Disabling history for now 267 | return 268 | 269 | map = self.history[bookmark] 270 | 271 | for obj in context.selected_objects: 272 | if obj.type == 'MESH': 273 | bm = map[obj] 274 | 275 | if obj.mode == 'OBJECT': 276 | #self.edit_object 277 | mesh = obj.data 278 | bm.to_mesh(mesh) 279 | mesh.update() 280 | elif obj.mode == 'EDIT': 281 | objBm = bmesh.from_edit_mesh(obj.data) 282 | #TODO: Somehow copy bm data to objBm 283 | 284 | #bm.clear() 285 | #bmesh.update_edit_mesh(obj.data) 286 | 287 | def history_undo_to_snapshot(self, context, idx): 288 | if True: 289 | #Disabling history for now 290 | return 291 | 292 | if idx < 0 or idx >= len(self.history): 293 | return 294 | 295 | self.history_idx = idx 296 | 297 | map = self.history[self.history_idx] 298 | 299 | for obj in context.selected_objects: 300 | if obj.type == 'MESH': 301 | bm = map[obj] 302 | 303 | mesh = obj.data 304 | if obj.mode == 'OBJECT': 305 | bm.to_mesh(mesh) 306 | mesh.update() 307 | elif obj.mode == 'EDIT': 308 | bm.update_edit_mesh(mesh) 309 | 310 | def history_clear(self, context): 311 | for key in self.history_bookmarks: 312 | map = self.history_bookmarks[key] 313 | self.free_snapshot(map) 314 | 315 | for map in self.history: 316 | self.free_snapshot(map) 317 | 318 | self.history = [] 319 | self.history_idx = -1 320 | 321 | 322 | def dab_brush(self, context, event): 323 | mouse_pos = (event.mouse_region_x, event.mouse_region_y) 324 | 325 | region = context.region 326 | rv3d = context.region_data 327 | 328 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos) 329 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos) 330 | 331 | viewlayer = bpy.context.view_layer 332 | 333 | hit_object = None 334 | location = None 335 | normal = None 336 | index = None 337 | 338 | if self.edit_object == None: 339 | hit_object, location, normal, face_index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector) 340 | else: 341 | l2w = self.edit_object.matrix_world 342 | w2l = l2w.inverted() 343 | local_ray_origin = w2l @ ray_origin 344 | local_view_vector = mul_vector(w2l, view_vector) 345 | 346 | if self.edit_object.mode == 'OBJECT': 347 | hit_object, location, normal, index = self.edit_object.ray_cast(local_ray_origin, local_view_vector) 348 | object = self.edit_object 349 | 350 | location = l2w @ location 351 | 352 | if self.edit_object.mode == 'EDIT': 353 | bm = bmesh.from_edit_mesh(self.edit_object.data) 354 | tree = mathutils.bvhtree.BVHTree.FromBMesh(bm) 355 | location, normal, index, distance = tree.ray_cast(local_ray_origin, local_view_vector) 356 | hit_object = location != None 357 | object = self.edit_object 358 | 359 | location = l2w @ location 360 | 361 | 362 | # print("hit obj:%s" % (str(hit_object))) 363 | 364 | center = None 365 | center_count = 0 366 | 367 | brush_radius = context.scene.uv_brush_props.radius 368 | strength = context.scene.uv_brush_props.strength 369 | use_pressure = context.scene.uv_brush_props.use_pressure 370 | 371 | if hit_object and len(self.stroke_trail) > 0: 372 | 373 | if self.edit_object == None: 374 | self.edit_object = object 375 | # print("--------Edit object uvs") 376 | 377 | l2w = object.matrix_world 378 | n2w = l2w.copy() 379 | n2w.invert() 380 | n2w.transpose() 381 | 382 | mesh = object.data 383 | if self.edit_object.mode == 'EDIT': 384 | bm = bmesh.from_edit_mesh(mesh) 385 | elif self.edit_object.mode == 'OBJECT': 386 | bm = bmesh.new() 387 | bm.from_mesh(mesh) 388 | 389 | # uvLayer = mesh.uv_layers.active.data 390 | uv_layer = bm.loops.layers.uv.active 391 | 392 | vert_trackers = [VertexTracker(v) for v in bm.verts] 393 | 394 | for face in bm.faces: 395 | l0 = face.loops[0] 396 | l1 = face.loops[1] 397 | l2 = face.loops[2] 398 | 399 | v0pos = l2w @ l0.vert.co 400 | v1pos = l2w @ l1.vert.co 401 | v2pos = l2w @ l2.vert.co 402 | 403 | # print("v0pos: %s v1pos: %s v2pos: %s " % (str(v0pos), str(v1pos), str(v2pos))) 404 | 405 | v1 = v1pos - v0pos 406 | v2 = v2pos - v0pos 407 | 408 | # print("v1: %s v2: %s norm: %s " % (str(v1), str(v2), str(p.normal))) 409 | 410 | faceNormal = mul_vector(n2w, face.normal) 411 | 412 | dragP0 = project_point_onto_plane(self.stroke_trail[-1], v0pos, faceNormal) 413 | dragP1 = project_point_onto_plane(location, v0pos, faceNormal) 414 | 415 | # print("dragP0: %s dragP1: %s" % (str(dragP0), str(dragP1))) 416 | 417 | uv0 = l0[uv_layer].uv 418 | uv1 = l1[uv_layer].uv 419 | uv2 = l2[uv_layer].uv 420 | # uv0 = uvLayer[p.loop_indices[0]].uv 421 | # uv1 = uvLayer[p.loop_indices[1]].uv 422 | # uv2 = uvLayer[p.loop_indices[2]].uv 423 | 424 | # print("uv0: %s uv1: %s uv2: %s" % (str(uv0), str(uv1), str(uv2))) 425 | 426 | 427 | locCo0 = express_in_basis(dragP0 - v0pos, v1, v2, faceNormal) 428 | locCo1 = express_in_basis(dragP1 - v0pos, v1, v2, faceNormal) 429 | 430 | # print("locCo0: %s locCo1: %s" % (str(locCo0), str(locCo1))) 431 | 432 | dragUv0 = (uv1 - uv0) * locCo0.x + (uv2 - uv0) * locCo0.y + uv0 433 | dragUv1 = (uv1 - uv0) * locCo1.x + (uv2 - uv0) * locCo1.y + uv0 434 | dUv = dragUv1 - dragUv0 435 | 436 | # print("dragUv0: %s dragUv1: %s dUv: %s" % (str(dragUv0), str(dragUv1), str(dUv))) 437 | 438 | # print ("dUv.magnitude " + str(dUv.magnitude)) 439 | 440 | # print("loop total:%d" % (p.loop_total)) 441 | 442 | for loop in face.loops: 443 | 444 | loop_uv = loop[uv_layer].uv 445 | v = loop.vert 446 | pos = l2w @ v.co 447 | dist = (pos - location).magnitude 448 | # print ("dist " + str(dist)) 449 | if dist < brush_radius: 450 | atten = 1 - dist / brush_radius 451 | atten *= strength 452 | if use_pressure: 453 | atten *= event.pressure 454 | vert_trackers[v.index].considerUv(loop_uv.copy(), dist, loop_uv - atten * dUv) 455 | 456 | #Write new uvs back to mesh 457 | 458 | for face in bm.faces: 459 | for loop in face.loops: 460 | # loop = mesh.loops[loop_idx] 461 | # print("lookup vertidx %s uv %s " % (str(loop.vertex_index), str(uvLayer[loop_idx].uv))) 462 | 463 | loop_uv = loop[uv_layer].uv 464 | tracker = vert_trackers[loop.vert.index] 465 | newUv = tracker.getNewUv(loop_uv) 466 | if newUv != None: 467 | loop[uv_layer].uv = newUv 468 | 469 | 470 | if self.edit_object.mode == 'EDIT': 471 | bmesh.update_edit_mesh(mesh) 472 | elif self.edit_object.mode == 'OBJECT': 473 | bm.to_mesh(mesh) 474 | bm.free() 475 | 476 | if hit_object: 477 | self.stroke_trail.append(location) 478 | 479 | else: 480 | self.stroke_trail = [] 481 | self.edit_object = None 482 | 483 | def mouse_move(self, context, event): 484 | mouse_pos = (event.mouse_region_x, event.mouse_region_y) 485 | 486 | ctx = bpy.context 487 | 488 | region = context.region 489 | rv3d = context.region_data 490 | 491 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos) 492 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos) 493 | 494 | viewlayer = bpy.context.view_layer 495 | result, location, normal, index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector) 496 | 497 | #Brush cursor display 498 | if result: 499 | self.show_cursor = True 500 | self.cursor_pos = location 501 | self.cursor_normal = normal 502 | self.cursor_object = object 503 | self.cursor_matrix = matrix 504 | else: 505 | self.show_cursor = False 506 | 507 | if self.dragging: 508 | self.dab_brush(context, event) 509 | pass 510 | 511 | 512 | def mouse_click(self, context, event): 513 | if event.value == "PRESS": 514 | 515 | mouse_pos = (event.mouse_region_x, event.mouse_region_y) 516 | region = context.region 517 | rv3d = context.region_data 518 | 519 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos) 520 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos) 521 | 522 | viewlayer = bpy.context.view_layer 523 | result, location, normal, index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector) 524 | 525 | if result == False or object.select_get() == False or object.type != 'MESH': 526 | return {'PASS_THROUGH'} 527 | 528 | self.dragging = True 529 | self.stroke_trail = [] 530 | 531 | self.edit_object = object 532 | 533 | self.dab_brush(context, event) 534 | 535 | 536 | # self.init_mesh = bmesh.new() 537 | # self.init_mesh.copyFrom(object) 538 | 539 | elif event.value == "RELEASE": 540 | self.dragging = False 541 | self.edit_object = None 542 | 543 | self.history_snapshot(context) 544 | 545 | 546 | return {'RUNNING_MODAL'} 547 | 548 | @classmethod 549 | def poll(cls, context): 550 | return context.active_object is not None 551 | 552 | def modal(self, context, event): 553 | # print("modal evTyp:%s evVal:%s" % (str(event.type), str(event.value))) 554 | context.area.tag_redraw() 555 | 556 | if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}: 557 | # allow navigation 558 | return {'PASS_THROUGH'} 559 | 560 | elif event.type == 'MOUSEMOVE': 561 | context.window.cursor_set("PAINT_BRUSH") 562 | 563 | self.mouse_move(context, event) 564 | 565 | if self.dragging: 566 | return {'RUNNING_MODAL'} 567 | else: 568 | return {'PASS_THROUGH'} 569 | 570 | elif event.type == 'LEFTMOUSE': 571 | return self.mouse_click(context, event) 572 | 573 | # elif event.type == 'RIGHTMOUSE': 574 | # mouse_pos = (event.mouse_region_x, event.mouse_region_y) 575 | # print(" pos %s" % str(mouse_pos)) 576 | 577 | # bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 578 | # self.show_cursor = False 579 | 580 | # return {'FINISHED'} 581 | 582 | elif event.type in {'Z'}: 583 | if event.ctrl: 584 | if event.shift: 585 | if event.value == "RELEASE": 586 | self.history_redo(context) 587 | return {'RUNNING_MODAL'} 588 | else: 589 | if event.value == "RELEASE": 590 | self.history_undo(context) 591 | 592 | return {'RUNNING_MODAL'} 593 | 594 | return {'RUNNING_MODAL'} 595 | 596 | elif event.type in {'RET'}: 597 | if event.value == 'RELEASE': 598 | context.window.cursor_set("DEFAULT") 599 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 600 | self.history_clear(context) 601 | return {'FINISHED'} 602 | return {'RUNNING_MODAL'} 603 | 604 | elif event.type in {'PAGE_UP', 'RIGHT_BRACKET'}: 605 | if event.value == "PRESS": 606 | brush_radius = context.scene.uv_brush_props.radius 607 | brush_radius = brush_radius + .1 608 | context.scene.uv_brush_props.radius = brush_radius 609 | return {'RUNNING_MODAL'} 610 | 611 | elif event.type in {'PAGE_DOWN', 'LEFT_BRACKET'}: 612 | if event.value == "PRESS": 613 | brush_radius = context.scene.uv_brush_props.radius 614 | brush_radius = max(brush_radius - .1, .1) 615 | context.scene.uv_brush_props.radius = brush_radius 616 | return {'RUNNING_MODAL'} 617 | 618 | elif event.type == 'ESC': 619 | if event.value == 'RELEASE': 620 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 621 | context.window.cursor_set("DEFAULT") 622 | self.history_restore_bookmark(context, 0) 623 | self.history_clear(context) 624 | return {'CANCELLED'} 625 | return {'RUNNING_MODAL'} 626 | 627 | return {'PASS_THROUGH'} 628 | 629 | # def execute(self, context): 630 | # print("execute SimpleOperator") 631 | # return {'FINISHED'} 632 | 633 | def invoke(self, context, event): 634 | if context.area.type == 'VIEW_3D': 635 | # print("invoke evTyp:%s evVal:%s" % (str(event.type), str(event.value))) 636 | 637 | args = (self, context) 638 | self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback, args, 'WINDOW', 'POST_VIEW') 639 | 640 | redraw_all_viewports(context) 641 | self.history_clear(context) 642 | self.history_snapshot(context) 643 | self.history_snapshot(context, 0) 644 | 645 | context.window_manager.modal_handler_add(self) 646 | 647 | context.window.cursor_set("PAINT_BRUSH") 648 | 649 | return {'RUNNING_MODAL'} 650 | else: 651 | self.report({'WARNING'}, "View3D not found, cannot run operator") 652 | return {'CANCELLED'} 653 | 654 | 655 | 656 | #--------------------------- 657 | 658 | 659 | 660 | def register(): 661 | 662 | #Register tools 663 | bpy.utils.register_class(UvBrushToolSettings) 664 | bpy.utils.register_class(UvBrushToolOperator) 665 | 666 | bpy.types.Scene.uv_brush_props = bpy.props.PointerProperty(type=UvBrushToolSettings) 667 | 668 | def unregister(): 669 | bpy.utils.unregister_class(UvBrushToolSettings) 670 | bpy.utils.unregister_class(UvBrushToolOperator) 671 | 672 | del bpy.types.Scene.uv_brush_props 673 | 674 | 675 | if __name__ == "__main__": 676 | register() -------------------------------------------------------------------------------- /source/operators/uvLayoutPlane.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | 17 | import bpy 18 | import bpy.utils.previews 19 | import os 20 | #import bgl 21 | import blf 22 | import gpu 23 | import mathutils 24 | import math 25 | import bmesh 26 | 27 | from gpu_extras.batch import batch_for_shader 28 | from bpy_extras import view3d_utils 29 | from enum import Enum 30 | 31 | from .vecmath import * 32 | from .handles import * 33 | from .blenderUtil import * 34 | 35 | class UvPlaneLayoutSettings(bpy.types.PropertyGroup): 36 | init_layout : bpy.props.EnumProperty( 37 | items=( 38 | ('BOUNDS', "Bounds", "Fit to bounds of selected faces"), 39 | ('FACE', "Face", "Start with same UVs as active face"), 40 | ('GRID', "Grid", "Align UVs using grid of closest axis") 41 | ), 42 | default='BOUNDS' 43 | ) 44 | 45 | selected_faces_only : bpy.props.BoolProperty( 46 | name="Selected Faces Only", 47 | description="Only change uvs of selected faces", 48 | default = True 49 | ) 50 | 51 | clamp_to_basis : bpy.props.BoolProperty( 52 | name="Step by UVs", 53 | description="When you translate the control, snap to a multiple of the length of the UV vectors.", 54 | default = False 55 | ) 56 | 57 | clamp_scalar : bpy.props.FloatProperty( 58 | name="Step UV scalar", 59 | description="Step size when using step mode. 1 will step by the entire texture width, .5 by half the texture, etc.", 60 | default = 1 61 | ) 62 | 63 | relocate_origin : bpy.props.BoolProperty( 64 | name="Relocate Origin", 65 | description="If true, when you start in Face mode, the origin will be relocated to be close to the center of the active face.", 66 | default = True 67 | ) 68 | 69 | 70 | #--------------------------- 71 | 72 | class UvPlaneControl: 73 | 74 | def __init__(self, context): 75 | self.controlMtx = None 76 | 77 | props = context.scene.kitfox_uv_plane_layout_props 78 | init_layout = props.init_layout 79 | 80 | if init_layout == 'FACE': 81 | self.setProjFromActiveFace(context) 82 | elif init_layout == 'BOUNDS': 83 | self.setFromMeshes(context) 84 | elif init_layout == 'GRID': 85 | self.setFromGrid(context) 86 | 87 | 88 | self.handle00 = HandleCorner(self, mathutils.Matrix.Translation(-vecX - vecY), vecZ, mathutils.Vector((0, 0, 0))) 89 | self.handle02 = HandleCorner(self, mathutils.Matrix.Translation(-vecX + vecY), vecZ, mathutils.Vector((0, 1, 0))) 90 | self.handle20 = HandleCorner(self, mathutils.Matrix.Translation(vecX - vecY), vecZ, mathutils.Vector((1, 0, 0))) 91 | self.handle22 = HandleCorner(self, mathutils.Matrix.Translation(vecX + vecY), vecZ, mathutils.Vector((1, 1, 0))) 92 | 93 | self.handle10 = HandleEdge(self, mathutils.Matrix.Translation(-vecY), -vecY, mathutils.Vector((.5, 0, 0))) 94 | self.handle01 = HandleEdge(self, mathutils.Matrix.Translation(-vecX), -vecX, mathutils.Vector((0, .5, 0))) 95 | self.handle12 = HandleEdge(self, mathutils.Matrix.Translation(vecY), vecY, mathutils.Vector((.5, 1, 0))) 96 | self.handle21 = HandleEdge(self, mathutils.Matrix.Translation(vecX), vecX, mathutils.Vector((1, .5, 0))) 97 | 98 | self.handle11 = HandleTranslateOmni(self, mathutils.Matrix(), mathutils.Vector((.5, .5, 0))) 99 | 100 | self.handleTransX = HandleTranslateVector(self, mathutils.Matrix(), vecX, mathutils.Vector((1.3, .5, 0))) 101 | self.handleTransY = HandleTranslateVector(self, mathutils.Matrix(), vecY, mathutils.Vector((.5, 1.3, 0))) 102 | self.handleTransZ = HandleTranslateVector(self, mathutils.Matrix(), vecZ, mathutils.Vector((.5, .5, 1.3))) 103 | 104 | self.handleRotX = HandleRotateAxis(self, mathutils.Matrix.Translation(vecZero), vecX, vecX) 105 | self.handleRotY = HandleRotateAxis(self, mathutils.Matrix.Translation(vecZero), vecY, vecY) 106 | self.handleRotZ = HandleRotateAxis(self, mathutils.Matrix.Translation(vecZero), vecZ, vecZ) 107 | 108 | 109 | self.handle00.body.setColor((0, 0, 1, 1)) 110 | self.handle02.body.setColor((0, 1, 1, 1)) 111 | self.handle20.body.setColor((1, 0, 1, 1)) 112 | self.handle22.body.setColor((1, 1, 1, 1)) 113 | 114 | self.handleRotX.body.setColor((1, 0, 0, 1)) 115 | self.handleRotY.body.setColor((0, 1, 0, 1)) 116 | self.handleRotZ.body.setColor((0, 0, 1, 1)) 117 | 118 | self.handleTransX.body.setColor((1, 0, 0, 1)) 119 | self.handleTransY.body.setColor((0, 1, 0, 1)) 120 | self.handleTransZ.body.setColor((0, 0, 1, 1)) 121 | 122 | self.handles = [self.handle00, self.handle02, self.handle20, self.handle22, self.handle10, self.handle01, self.handle12, self.handle21, self.handle11, self.handleTransX, self.handleTransY, self.handleTransZ, self.handleRotX, self.handleRotY, self.handleRotZ] 123 | 124 | 125 | self.layoutHandles() 126 | self.updateUvs(context) 127 | 128 | 129 | def __del__(self): 130 | # print("UvPlaneControl DESTRUCT") 131 | for h in self.handles: 132 | del h 133 | 134 | 135 | def mouse_move(self, context, event): 136 | consumed = False 137 | for handle in self.handles: 138 | if handle.mouse_move(context, event): 139 | consumed = True 140 | break 141 | 142 | return consumed 143 | 144 | def updateUvs(self, context): 145 | #update uvs 146 | w2uv = self.controlMtx.inverted() 147 | 148 | props = context.scene.kitfox_uv_plane_layout_props 149 | selected_faces_only = props.selected_faces_only 150 | # print("self.controlMtx %s" % (str(self.controlMtx))) 151 | # print("w2uv %s" % (str(w2uv))) 152 | 153 | for obj in context.selected_objects: 154 | if obj.type != "MESH": 155 | continue 156 | 157 | l2w = obj.matrix_world 158 | 159 | mesh = obj.data 160 | 161 | if obj.mode == 'EDIT': 162 | bm = bmesh.from_edit_mesh(mesh) 163 | elif obj.mode == 'OBJECT': 164 | bm = bmesh.new() 165 | bm.from_mesh(mesh) 166 | 167 | 168 | uv_layer = bm.loops.layers.uv.verify() 169 | 170 | for face in bm.faces: 171 | if not selected_faces_only or face.select: 172 | for loop in face.loops: 173 | loop_uv = loop[uv_layer] 174 | 175 | uvPos = w2uv @ l2w @ loop.vert.co 176 | 177 | #print("worldPos %s" % (str(uvPos))) 178 | #print("worldPos %s" % (str(uvPos))) 179 | loop_uv.uv = uvPos.xy 180 | 181 | if obj.mode == 'EDIT': 182 | bmesh.update_edit_mesh(mesh) 183 | elif obj.mode == 'OBJECT': 184 | bm.to_mesh(mesh) 185 | bm.free() 186 | 187 | 188 | 189 | def mouse_click(self, context, event): 190 | consumed = False 191 | for handle in self.handles: 192 | if handle.mouse_click(context, event): 193 | consumed = True 194 | redraw_all_viewports(context) 195 | break 196 | 197 | return consumed 198 | 199 | def layoutHandles(self): 200 | i = self.controlMtx.col[0].to_3d() 201 | j = self.controlMtx.col[1].to_3d() 202 | k = self.controlMtx.col[2].to_3d() 203 | h = self.controlMtx.col[3].to_3d() 204 | 205 | # print("layout Handles " + str(self.controlMtx)) 206 | # print("layout Handles i " + str(i)) 207 | # print("layout Handles j " + str(j)) 208 | # print("layout Handles k " + str(k)) 209 | 210 | self.handle00.transform = self.controlMtx @ mathutils.Matrix.Translation((0, 0, 0)) 211 | self.handle00.constraint.planeNormal = k 212 | 213 | self.handle02.transform = self.controlMtx @ mathutils.Matrix.Translation((0, 1, 0)) 214 | self.handle02.constraint.planeNormal = k 215 | 216 | self.handle20.transform = self.controlMtx @ mathutils.Matrix.Translation((1, 0, 0)) 217 | self.handle20.constraint.planeNormal = k 218 | 219 | self.handle22.transform = self.controlMtx @ mathutils.Matrix.Translation((1, 1, 0)) 220 | self.handle22.constraint.planeNormal = k 221 | 222 | 223 | self.handle01.transform = self.controlMtx @ mathutils.Matrix.Translation(mathutils.Vector((0, .5, 0))) 224 | self.handle01.constraint.vector = -i 225 | 226 | self.handle21.transform = self.controlMtx @ mathutils.Matrix.Translation(mathutils.Vector((1, .5, 0))) 227 | self.handle21.constraint.vector = i 228 | 229 | self.handle10.transform = self.controlMtx @ mathutils.Matrix.Translation(mathutils.Vector((.5, 0, 0))) 230 | self.handle10.constraint.vector = -j 231 | 232 | self.handle12.transform = self.controlMtx @ mathutils.Matrix.Translation(mathutils.Vector((.5, 1, 0))) 233 | self.handle12.constraint.vector = j 234 | 235 | self.handle11.transform = self.controlMtx @ mathutils.Matrix.Translation(self.handle11.posControl) 236 | 237 | self.handleTransX.transform = self.controlMtx @ mathutils.Matrix.Translation(self.handleTransX.posControl) 238 | self.handleTransX.constraint.vector = i 239 | 240 | self.handleTransY.transform = self.controlMtx @ mathutils.Matrix.Translation(self.handleTransY.posControl) 241 | self.handleTransY.constraint.vector = j 242 | 243 | self.handleTransZ.transform = self.controlMtx @ mathutils.Matrix.Translation(self.handleTransZ.posControl) 244 | self.handleTransZ.constraint.vector = k 245 | 246 | center = mathutils.Vector((.5, .5, 0)) 247 | self.handleRotX.transform = self.controlMtx @ mathutils.Matrix.Translation(center) @ mathutils.Matrix.Rotation(math.radians(90), 4, 'Y') 248 | self.handleRotX.constraint.planeNormal = i 249 | self.handleRotX.constraint.planeOrigin = self.controlMtx @ self.handleRotX.pivot 250 | 251 | self.handleRotY.transform = self.controlMtx @ mathutils.Matrix.Translation(center) @ mathutils.Matrix.Rotation(math.radians(90), 4, 'X') 252 | self.handleRotY.constraint.planeNormal = j 253 | self.handleRotY.constraint.planeOrigin = self.controlMtx @ self.handleRotY.pivot 254 | 255 | self.handleRotZ.transform = self.controlMtx @ mathutils.Matrix.Translation(center) 256 | self.handleRotZ.constraint.planeNormal = k 257 | self.handleRotZ.constraint.planeOrigin = self.controlMtx @ self.handleRotZ.pivot 258 | 259 | 260 | def updateProjectionMatrix(self, context, matrix): 261 | self.controlMtx = matrix 262 | self.layoutHandles() 263 | self.updateUvs(context) 264 | redraw_all_viewports(context) 265 | 266 | 267 | def findTangent(self, norm): 268 | if 1 - abs(norm.normalized().dot(vecZ)) < .0001: 269 | return vecX.copy() 270 | 271 | tan = norm.cross(vecZ) 272 | tan.normalize() 273 | return tan 274 | 275 | 276 | def setProjFromActiveFace(self, context): 277 | obj = context.active_object 278 | if obj == None or obj.type != 'MESH': 279 | self.controlMtx = None 280 | return 281 | 282 | props = context.scene.kitfox_uv_plane_layout_props 283 | relocate_origin = props.relocate_origin 284 | 285 | bm = None 286 | 287 | if obj.mode == 'EDIT': 288 | bm = bmesh.from_edit_mesh(obj.data) 289 | elif obj.mode == 'OBJECT': 290 | bm = bmesh.new() 291 | bm.from_mesh(obj.data) 292 | 293 | # print("active face idx " + str(bm.faces.active)) 294 | face = bm.faces.active 295 | if face == None: 296 | bm.faces.ensure_lookup_table() 297 | face = bm.faces[0] 298 | 299 | l2w = obj.matrix_world 300 | n2w = l2w.copy() 301 | n2w.invert() 302 | n2w.transpose() 303 | 304 | bestNormal = n2w @ face.normal 305 | bestCenter = l2w @ face.calc_center_median() 306 | 307 | uv_layer = bm.loops.layers.uv.active 308 | 309 | l0 = face.loops[0] 310 | l1 = face.loops[1] 311 | l2 = face.loops[2] 312 | 313 | p0 = l2w @ face.verts[0].co 314 | p1 = l2w @ face.verts[1].co 315 | p2 = l2w @ face.verts[2].co 316 | 317 | # print("p0 " + str(p0)) 318 | # print("p1 " + str(p1)) 319 | # print("p2 " + str(p2)) 320 | 321 | p3 = p0 - bestNormal 322 | 323 | uv0 = l0[uv_layer].uv 324 | uv1 = l1[uv_layer].uv 325 | uv2 = l2[uv_layer].uv 326 | 327 | #if uvs don't form the basis of a plane, artificially create one 328 | duv1 = uv1 - uv0 329 | duv2 = uv2 - uv0 330 | if duv1.magnitude < .0001 and duv2.magnitude < .0001: 331 | uv1 = uv0 + mathutils.Vector((1, 0, 0)) 332 | uv2 = uv0 + mathutils.Vector((0, 1, 0)) 333 | 334 | elif duv1.magnitude < .0001: 335 | uv1.x = -duv2.y 336 | uv1.y = duv2.x 337 | uv1 += uv0 338 | 339 | elif duv2.magnitude < .0001 or (uv2 - uv1).magnitude < .0001: 340 | uv2.x = duv1.y 341 | uv2.y = -duv1.x 342 | uv2 += uv0 343 | 344 | 345 | # print("uv0 " + str(uv0)) 346 | # print("uv1 " + str(uv1)) 347 | # print("uv2 " + str(uv2)) 348 | # print("duv1 " + str(duv1)) 349 | # print("duv2 " + str(duv2)) 350 | 351 | U = mathutils.Matrix(( 352 | (uv0.x, uv0.y, 0, 1), 353 | (uv1.x, uv1.y, 0, 1), 354 | (uv2.x, uv2.y, 0, 1), 355 | (uv0.x, uv0.y, 1, 1) 356 | )) 357 | U.transpose() 358 | # print("mtx U " + str(U)) 359 | U.invert() 360 | # print("mtx U-1 " + str(U)) 361 | 362 | P = mathutils.Matrix(( 363 | (p0.x, p0.y, p0.z, 1), 364 | (p1.x, p1.y, p1.z, 1), 365 | (p2.x, p2.y, p2.z, 1), 366 | (p3.x, p3.y, p3.z, 1) 367 | )) 368 | P.transpose() 369 | 370 | # print("mtx P " + str(P)) 371 | 372 | C = P @ U 373 | 374 | #Center UVs on face by subtracting out integer multiples of u, v vectors 375 | if relocate_origin: 376 | CI = C.inverted() 377 | 378 | bestCenterUv = CI @ bestCenter 379 | # bestCenterUvFloor = floor_vector(bestCenterUv + mathutils.Vector((.5, .5, .5))) 380 | bestCenterUvFloor = floor_vector(bestCenterUv) 381 | 382 | C = C @ mathutils.Matrix.Translation(bestCenterUvFloor) 383 | 384 | 385 | self.controlMtx = C 386 | 387 | # print("mtx C " + str(C)) 388 | 389 | # CI = C.copy() 390 | # CI.invert() 391 | # print("mtx C-1 " + str(CI)) 392 | 393 | if obj.mode == 'OBJECT': 394 | bm.free() 395 | 396 | 397 | def setFromGrid(self, context): 398 | obj = context.active_object 399 | if obj == None or obj.type != 'MESH': 400 | self.controlMtx = None 401 | return 402 | 403 | #Find active face 404 | bm = None 405 | if obj.mode == 'EDIT': 406 | bm = bmesh.from_edit_mesh(obj.data) 407 | elif obj.mode == 'OBJECT': 408 | bm = bmesh.new() 409 | bm.from_mesh(obj.data) 410 | 411 | # print("active face idx " + str(bm.faces.active)) 412 | face = bm.faces.active 413 | if face == None: 414 | bm.faces.ensure_lookup_table() 415 | face = bm.faces[0] 416 | 417 | l2w = obj.matrix_world 418 | n2w = l2w.copy() 419 | n2w.invert() 420 | n2w.transpose() 421 | 422 | activeNormal = n2w @ face.normal 423 | activeCenter = l2w @ face.calc_center_median() 424 | 425 | if obj.mode == 'OBJECT': 426 | bm.free() 427 | 428 | #Grid projection 429 | scale = context.space_data.overlay.grid_scale 430 | center = snap_to_grid(activeCenter, scale) 431 | 432 | axis = closest_axis(activeNormal) 433 | if axis == Axis.X: 434 | i = vecY * scale 435 | j = vecZ * scale 436 | k = vecX * scale 437 | center.x = activeCenter.x 438 | elif axis == Axis.Y: 439 | i = vecX * scale 440 | j = vecZ * scale 441 | k = vecY * scale 442 | center.y = activeCenter.y 443 | elif axis == Axis.Z: 444 | i = vecX * scale 445 | j = vecY * scale 446 | k = vecZ * scale 447 | center.z = activeCenter.z 448 | 449 | i = i.to_4d() 450 | i.w = 0 451 | j = j.to_4d() 452 | j.w = 0 453 | k = k.to_4d() 454 | k.w = 0 455 | h = center.to_4d() 456 | 457 | self.controlMtx = mathutils.Matrix((i, j, k, h)) 458 | self.controlMtx.transpose() 459 | 460 | 461 | def setFromMeshes(self, context): 462 | 463 | obj = context.active_object 464 | if obj == None or obj.type != 'MESH': 465 | self.controlMtx = None 466 | return 467 | 468 | props = context.scene.kitfox_uv_plane_layout_props 469 | selected_faces_only = props.selected_faces_only 470 | 471 | mesh = obj.data 472 | l2w = obj.matrix_world 473 | n2w = l2w.copy() 474 | n2w.invert() 475 | n2w.transpose() 476 | 477 | mesh = obj.data 478 | bestNormal = None 479 | bestCenter = None 480 | 481 | bm = None 482 | 483 | if obj.mode == 'EDIT': 484 | bm = bmesh.from_edit_mesh(mesh) 485 | print("active face idx " + str(bm.faces.active)) 486 | face = bm.faces.active 487 | if face == None: 488 | face = bm.faces[0] 489 | bestNormal = n2w @ face.normal 490 | bestCenter = l2w @ face.calc_center_median() 491 | elif obj.mode == 'OBJECT': 492 | print("active poly idx " + str(mesh.polygons.active)) 493 | bestPoly = mesh.polygons[mesh.polygons.active] 494 | 495 | bestNormal = n2w @ bestPoly.normal 496 | bestCenter = l2w @ bestPoly.center 497 | 498 | bm = bmesh.new() 499 | bm.from_mesh(mesh) 500 | 501 | 502 | #Build matrix from world space to face space 503 | tangent = self.findTangent(bestNormal) 504 | binormal = bestNormal.cross(tangent) 505 | 506 | #print("tangent %s binormal %s " % (str(tangent), str(binormal))) 507 | 508 | tangent = tangent.to_4d() 509 | tangent.w = 0 510 | binormal = binormal.to_4d() 511 | binormal.w = 0 512 | bestNormal = bestNormal.to_4d() 513 | bestNormal.w = 0 514 | center = bestCenter.to_4d() 515 | center.w = 1 516 | poly2w = mathutils.Matrix((tangent.to_4d(), binormal.to_4d(), bestNormal.to_4d(), center)) 517 | poly2w.transpose() 518 | w2poly = poly2w.inverted() 519 | 520 | #print("poly2w %s\n" % (str(poly2w))) 521 | #print("w2poly %s\n" % (str(w2poly))) 522 | 523 | #find bounds of mesh projected along normal of chosen polygon 524 | minX = None 525 | maxX = None 526 | minY = None 527 | maxY = None 528 | for obj in context.selected_objects: 529 | if obj.type != "MESH": 530 | continue 531 | 532 | mesh = obj.data 533 | if obj.mode == 'EDIT': 534 | bm = bmesh.from_edit_mesh(mesh) 535 | elif obj.mode == 'OBJECT': 536 | bm = bmesh.new() 537 | bm.from_mesh(mesh) 538 | 539 | 540 | l2w = obj.matrix_world 541 | l2poly = w2poly @ l2w 542 | 543 | for f in bm.faces: 544 | if not selected_faces_only or f.select: 545 | for v in f.verts: 546 | # v = mesh.vertices[vIdx] 547 | 548 | faceV = l2poly @ v.co 549 | 550 | # print("mapping v %s -> %s " % (str(v.co), str(faceV))) 551 | 552 | minX = faceV.x if minX == None else min(faceV.x, minX) 553 | maxX = faceV.x if maxX == None else max(faceV.x, maxX) 554 | minY = faceV.y if minY == None else min(faceV.y, minY) 555 | maxY = faceV.y if maxY == None else max(faceV.y, maxY) 556 | 557 | if obj.mode == 'OBJECT': 558 | bm.free() 559 | 560 | if minX == None: 561 | return 562 | 563 | #print("minX %s maxX %s minY %s maxY %s " % (str(minX), str(maxX), str(minY), str(maxY))) 564 | 565 | dx = maxX - minX 566 | dy = maxY - minY 567 | # cx = (maxX + minX) / 2 568 | # cy = (maxY + minY) / 2 569 | cx = minX 570 | cy = minY 571 | ctrlCenter = cx * tangent + cy * binormal + center 572 | #print("dx %s dy %s cx %s cy %s " % (str(dx), str(dy), str(cx), str(cy))) 573 | #print("cx tan %s cy tan %s" % (str(cx * tangent), str(cy * binormal))) 574 | 575 | # self.controlMtx = mathutils.Matrix((tangent * dx / 2, binormal * dy / 2, bestNormal, ctrlCenter)) 576 | self.controlMtx = mathutils.Matrix((tangent * dx, binormal * dy, bestNormal, ctrlCenter)) 577 | self.controlMtx.transpose() 578 | 579 | #print("controlMtx %s" % (str(self.controlMtx))) 580 | 581 | 582 | 583 | 584 | 585 | def draw(self, context): 586 | #print("draign control") 587 | 588 | # rv3d = context.space_data.region_3d 589 | # w2v = rv3d.view_matrix 590 | # v2w = w2v.inverted() 591 | # print("view_matrix " + str(w2v)) 592 | # print("view_matrix I " + str(v2w)) 593 | 594 | # win2v = rv3d.window_matrix 595 | # print("window_matrix " + str(win2v)) 596 | # print("window_matrix I " + str(win2v.inverted())) 597 | 598 | # rv3d.view_perspective 599 | # rv3d.is_perspective 600 | # persp = rv3d.perspective_matrix 601 | # print("perspective_matrix " + str(persp)) 602 | # print("perspective_matrix I " + str(persp.inverted())) 603 | 604 | #--------------------------- 605 | shader = gpu.shader.from_builtin('UNIFORM_COLOR') 606 | # batchCube = batch_for_shader(shader, 'LINES', {"pos": coordsCube}) 607 | batchCube = batch_for_shader(shader, 'LINE_STRIP', {"pos": coordsSquare_strip}) 608 | 609 | 610 | if self.controlMtx == None: 611 | return 612 | 613 | shader.bind(); 614 | #bgl.glEnable(bgl.GL_DEPTH_TEST) 615 | 616 | gpu.matrix.push() 617 | 618 | gpu.matrix.multiply_matrix(self.controlMtx) 619 | shader.uniform_float("color", (1, 0, 1, 1)) 620 | batchCube.draw(shader) 621 | 622 | gpu.matrix.pop() 623 | 624 | #bgl.glDisable(bgl.GL_DEPTH_TEST) 625 | 626 | # print(" DRAW HANDLESs") 627 | for handle in self.handles: 628 | # print(" Drawing handle " + str(handle)) 629 | handle.draw(context) 630 | 631 | #--------------------------- 632 | 633 | 634 | 635 | def draw_callback(self, context): 636 | 637 | ctx = bpy.context 638 | 639 | if self.control != None: 640 | self.control.draw(context) 641 | 642 | 643 | #--------------------------- 644 | 645 | class UvLayoutPlaneOperator(bpy.types.Operator): 646 | """Plane projection for UVs""" 647 | bl_idname = "kitfox.uv_plane_layout_op" 648 | bl_label = "Uv Layout" 649 | bl_options = {"REGISTER", "UNDO"} 650 | 651 | 652 | def __init__(self, *args, **kwargs): 653 | super().__init__(*args, **kwargs) 654 | 655 | self.control = None 656 | 657 | 658 | def __del__(self): 659 | super().__del__() 660 | 661 | def mouse_move(self, context, event): 662 | 663 | consumed = False 664 | 665 | if self.control: 666 | self.control.mouse_move(context, event) 667 | consumed = True 668 | 669 | # for mesh_tracker in self.mesh_trackers: 670 | # if mesh_tracker.mouse_move(context, event): 671 | # consumed = True 672 | 673 | 674 | if consumed: 675 | return {'RUNNING_MODAL'} 676 | else: 677 | return {'PASS_THROUGH'} 678 | 679 | 680 | def mouse_click(self, context, event): 681 | 682 | consumed = False 683 | 684 | if self.control: 685 | self.control.mouse_click(context, event) 686 | consumed = True 687 | 688 | 689 | # for mesh_tracker in self.mesh_trackers: 690 | # if mesh_tracker.mouse_button(context, event): 691 | # consumed = True 692 | # break 693 | 694 | if consumed: 695 | return {'RUNNING_MODAL'} 696 | else: 697 | return {'PASS_THROUGH'} 698 | 699 | 700 | def modal(self, context, event): 701 | 702 | # context.area.tag_redraw() 703 | redraw_all_viewports(context) 704 | 705 | if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}: 706 | # allow navigation 707 | return {'PASS_THROUGH'} 708 | 709 | elif event.type == 'UP_ARROW': 710 | if event.value == 'PRESS': 711 | m = mathutils.Matrix.Diagonal(mathutils.Vector((1, 2, 1, 1))) 712 | self.control.updateProjectionMatrix(context, self.control.controlMtx @ m) 713 | return {'RUNNING_MODAL'} 714 | 715 | elif event.type == 'DOWN_ARROW': 716 | if event.value == 'PRESS': 717 | m = mathutils.Matrix.Diagonal(mathutils.Vector((1, .5, 1, 1))) 718 | self.control.updateProjectionMatrix(context, self.control.controlMtx @ m) 719 | return {'RUNNING_MODAL'} 720 | 721 | elif event.type == 'RIGHT_ARROW': 722 | if event.value == 'PRESS': 723 | m = mathutils.Matrix.Diagonal(mathutils.Vector((2, 1, 1, 1))) 724 | self.control.updateProjectionMatrix(context, self.control.controlMtx @ m) 725 | return {'RUNNING_MODAL'} 726 | 727 | elif event.type == 'LEFT_ARROW': 728 | if event.value == 'PRESS': 729 | m = mathutils.Matrix.Diagonal(mathutils.Vector((.5, 1, 1, 1))) 730 | self.control.updateProjectionMatrix(context, self.control.controlMtx @ m) 731 | return {'RUNNING_MODAL'} 732 | 733 | elif event.type == 'MOUSEMOVE': 734 | return self.mouse_move(context, event) 735 | 736 | elif event.type == 'LEFTMOUSE': 737 | return self.mouse_click(context, event) 738 | # return {'PASS_THROUGH'} 739 | # return {'RUNNING_MODAL'} 740 | 741 | elif event.type in {'RET'}: 742 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 743 | return {'FINISHED'} 744 | 745 | elif event.type in {'RIGHTMOUSE', 'ESC'}: 746 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW') 747 | return {'CANCELLED'} 748 | 749 | return {'PASS_THROUGH'} 750 | # return {'RUNNING_MODAL'} 751 | 752 | def isEmpty(self, context): 753 | props = context.scene.kitfox_uv_plane_layout_props 754 | selected_faces_only = props.selected_faces_only 755 | 756 | for obj in context.selected_objects: 757 | if obj.type == 'MESH': 758 | mesh = obj.data 759 | 760 | if selected_faces_only: 761 | if obj.mode == 'EDIT': 762 | bm = bmesh.from_edit_mesh(mesh) 763 | for f in bm.faces: 764 | if f.select: 765 | return False 766 | 767 | else: 768 | 769 | for p in mesh.polygons: 770 | if p.select: 771 | return False 772 | 773 | else: 774 | return False 775 | 776 | return True 777 | 778 | def invoke(self, context, event): 779 | 780 | if context.area.type == 'VIEW_3D': 781 | if self.isEmpty(context): 782 | self.report({'WARNING'}, "Nothing selected to apply projection to") 783 | return {'CANCELLED'} 784 | 785 | args = (self, context) 786 | 787 | # Add the region OpenGL drawing callback 788 | # draw in view space with 'POST_VIEW' and 'PRE_VIEW' 789 | self._context = context 790 | self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback, args, 'WINDOW', 'POST_VIEW') 791 | 792 | # context.area.tag_redraw() 793 | redraw_all_viewports(context) 794 | 795 | context.window_manager.modal_handler_add(self) 796 | 797 | if self.control: 798 | del self.control 799 | # for mt in self.mesh_trackers: 800 | # del mt 801 | 802 | self.control = UvPlaneControl(context) 803 | 804 | # self.mesh_trackers = [] 805 | # for obj in context.selected_objects: 806 | # if obj.type != "MESH": 807 | # continue 808 | # self.mesh_trackers.append(MeshTracker(obj)) 809 | # 810 | return {'RUNNING_MODAL'} 811 | else: 812 | self.report({'WARNING'}, "View3D not found, cannot run operator") 813 | return {'CANCELLED'} 814 | 815 | 816 | #--------------------------- 817 | 818 | 819 | def register(): 820 | bpy.utils.register_class(UvPlaneLayoutSettings) 821 | bpy.utils.register_class(UvLayoutPlaneOperator) 822 | 823 | bpy.types.Scene.kitfox_uv_plane_layout_props = bpy.props.PointerProperty(type=UvPlaneLayoutSettings) 824 | 825 | 826 | def unregister(): 827 | 828 | bpy.utils.unregister_class(UvPlaneLayoutSettings) 829 | bpy.utils.unregister_class(UvLayoutPlaneOperator) 830 | 831 | del bpy.types.Scene.kitfox_uv_plane_layout_props 832 | 833 | 834 | if __name__ == "__main__": 835 | register() 836 | 837 | 838 | -------------------------------------------------------------------------------- /source/operators/uvToolsPanel.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import bpy 17 | import bpy.utils.previews 18 | import os 19 | 20 | preview_collections = {} 21 | 22 | 23 | #--------------------------- 24 | 25 | class UvBrushPanel(bpy.types.Panel): 26 | 27 | """Properties Panel for the Uv Brush""" 28 | bl_label = "Uv Brush" 29 | bl_idname = "OBJECT_PT_uv_brush" 30 | bl_space_type = 'VIEW_3D' 31 | bl_region_type = 'UI' 32 | bl_category = "Kitfox - UV" 33 | 34 | 35 | 36 | @classmethod 37 | def poll(cls, context): 38 | obj = context.object 39 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 40 | 41 | def draw(self, context): 42 | layout = self.layout 43 | 44 | scene = context.scene 45 | settings = scene.uv_brush_props 46 | 47 | pcoll = preview_collections["main"] 48 | 49 | #-------------------------------- 50 | 51 | col = layout.column(); 52 | col.operator("kitfox.uv_brush_operator", text="Uv Brush", icon_value = pcoll["uvBrush"].icon_id) 53 | 54 | col.prop(settings, "radius") 55 | col.prop(settings, "strength") 56 | col.prop(settings, "use_pressure") 57 | 58 | layout.separator() 59 | 60 | 61 | #--------------------------- 62 | 63 | class UvPlaneProjectionPanel(bpy.types.Panel): 64 | 65 | """Properties Panel for the Uv Plane Projection""" 66 | bl_label = "Uv Plane Projection" 67 | bl_idname = "OBJECT_PT_kitfox_uv_brush" 68 | bl_space_type = 'VIEW_3D' 69 | bl_region_type = 'UI' 70 | bl_category = "Kitfox - UV" 71 | 72 | 73 | 74 | @classmethod 75 | def poll(cls, context): 76 | obj = context.object 77 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 78 | 79 | def draw(self, context): 80 | layout = self.layout 81 | 82 | scene = context.scene 83 | settings = scene.uv_brush_props 84 | 85 | pcoll = preview_collections["main"] 86 | 87 | #-------------------------------- 88 | 89 | planeLayout_props = scene.kitfox_uv_plane_layout_props 90 | 91 | col = layout.column(); 92 | col.operator("kitfox.uv_plane_layout_op", text="Uv Plane Project", icon_value = pcoll["uvBrush"].icon_id) 93 | col.prop(planeLayout_props, "selected_faces_only") 94 | col.prop(planeLayout_props, "clamp_to_basis") 95 | col.prop(planeLayout_props, "clamp_scalar") 96 | col.label(text = "Starting Layout:") 97 | col.prop(planeLayout_props, "init_layout", expand = True) 98 | if planeLayout_props.init_layout == 'FACE': 99 | col.prop(planeLayout_props, "relocate_origin") 100 | 101 | layout.separator() 102 | 103 | 104 | #--------------------------- 105 | 106 | class CopySymmetricUvsPanel(bpy.types.Panel): 107 | 108 | """Properties Panel for Copy Symmetric Uvs""" 109 | bl_label = "Copy Symmetric Uvs" 110 | bl_idname = "OBJECT_PT_kitfox_copy_symmetric_uvs" 111 | bl_space_type = 'VIEW_3D' 112 | bl_region_type = 'UI' 113 | bl_category = "Kitfox - UV" 114 | 115 | 116 | 117 | @classmethod 118 | def poll(cls, context): 119 | obj = context.object 120 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 121 | 122 | def draw(self, context): 123 | layout = self.layout 124 | 125 | scene = context.scene 126 | settings = scene.uv_brush_props 127 | 128 | pcoll = preview_collections["main"] 129 | 130 | #-------------------------------- 131 | 132 | settings_copy_sym = context.scene.kitfox_copy_symmetric_uvs 133 | 134 | col = layout.column(); 135 | col.operator("kitfox.copy_symmetric_uvs", text="Copy Symmetric UVs") 136 | 137 | col.prop(settings_copy_sym, "axis") 138 | col.prop(settings_copy_sym, "epsilon") 139 | 140 | layout.separator() 141 | 142 | 143 | 144 | #--------------------------- 145 | 146 | class TriplanarUnwrapPanel(bpy.types.Panel): 147 | 148 | """Properties Panel for Triplanar Unwrap""" 149 | bl_label = "Triplanar Unwrap" 150 | bl_idname = "OBJECT_PT_kitfox_triplanar_unwrap" 151 | bl_space_type = 'VIEW_3D' 152 | bl_region_type = 'UI' 153 | bl_category = "Kitfox - UV" 154 | 155 | 156 | 157 | @classmethod 158 | def poll(cls, context): 159 | obj = context.object 160 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 161 | 162 | def draw(self, context): 163 | layout = self.layout 164 | 165 | scene = context.scene 166 | settings = scene.uv_brush_props 167 | 168 | pcoll = preview_collections["main"] 169 | 170 | #-------------------------------- 171 | 172 | settings_tri = context.scene.triplanar_settings_props 173 | 174 | col = layout.column(); 175 | col.operator("kitfox.triplanar_uv_unwrap", text="Triplanar Unwrap") 176 | 177 | col.prop(settings_tri, "scale_uniform") 178 | row = col.row() 179 | if settings_tri.scale_uniform: 180 | row.prop(settings_tri, "scale_u", text = "Scale") 181 | else: 182 | row.prop(settings_tri, "scale_u") 183 | row.prop(settings_tri, "scale_v") 184 | 185 | col.prop(settings_tri, "use_grid_scale") 186 | 187 | layout.separator() 188 | 189 | #--------------------------- 190 | 191 | class UvToolsPanel(bpy.types.Panel): 192 | 193 | """Properties Panel for the Uv Plane Projection""" 194 | bl_label = "Other" 195 | bl_idname = "OBJECT_PT_kitfox_uv_tools" 196 | bl_space_type = 'VIEW_3D' 197 | bl_region_type = 'UI' 198 | bl_category = "Kitfox - UV" 199 | 200 | 201 | 202 | @classmethod 203 | def poll(cls, context): 204 | obj = context.object 205 | return obj != None and (obj.mode == 'EDIT' or obj.mode == 'OBJECT') 206 | 207 | def draw(self, context): 208 | layout = self.layout 209 | 210 | scene = context.scene 211 | settings = scene.uv_brush_props 212 | 213 | pcoll = preview_collections["main"] 214 | 215 | col = layout.column(); 216 | col.prop(bpy.context.scene.tool_settings, "use_transform_correct_face_attributes") 217 | 218 | #--------------------------- 219 | 220 | 221 | def menu_start_uvBrush(self, context): 222 | self.layout.operator_context = 'INVOKE_DEFAULT' 223 | self.layout.operator("kitfox.uv_brush_operator") 224 | 225 | def menu_start_planarProject(self, context): 226 | self.layout.operator_context = 'INVOKE_DEFAULT' 227 | self.layout.operator("kitfox.uv_plane_layout_op") 228 | 229 | def menu_start_copySymmetricUvs(self, context): 230 | self.layout.operator("kitfox.copy_symmetric_uvs") 231 | 232 | def menu_start_triplanarProject(self, context): 233 | self.layout.operator("kitfox.triplanar_uv_unwrap") 234 | 235 | def register(): 236 | 237 | #Load icons 238 | icon_path = "../icons" 239 | if __name__ == "__main__": 240 | icon_path = "../../source/icons" 241 | 242 | icons_dir = os.path.join(os.path.dirname(__file__), icon_path) 243 | 244 | # print("icons dir: " + str(icons_dir)) 245 | 246 | pcoll = bpy.utils.previews.new() 247 | pcoll.load("uvBrush", os.path.join(icons_dir, "uvBrush.png"), 'IMAGE') 248 | preview_collections["main"] = pcoll 249 | 250 | #Register panels 251 | bpy.utils.register_class(UvBrushPanel) 252 | bpy.utils.register_class(UvPlaneProjectionPanel) 253 | bpy.utils.register_class(CopySymmetricUvsPanel) 254 | bpy.utils.register_class(TriplanarUnwrapPanel) 255 | bpy.utils.register_class(UvToolsPanel) 256 | 257 | #Register menus 258 | bpy.types.VIEW3D_MT_uv_map.append(menu_start_uvBrush) 259 | bpy.types.VIEW3D_MT_uv_map.append(menu_start_planarProject) 260 | bpy.types.VIEW3D_MT_uv_map.append(menu_start_copySymmetricUvs) 261 | bpy.types.VIEW3D_MT_uv_map.append(menu_start_triplanarProject) 262 | 263 | def unregister(): 264 | #Unregister panels 265 | bpy.utils.unregister_class(UvBrushPanel) 266 | bpy.utils.unregister_class(UvPlaneProjectionPanel) 267 | bpy.utils.unregister_class(CopySymmetricUvsPanel) 268 | bpy.utils.unregister_class(TriplanarUnwrapPanel) 269 | bpy.utils.unregister_class(UvToolsPanel) 270 | 271 | #Unregister menus 272 | bpy.types.VIEW3D_MT_uv_map.remove(menu_start_uvBrush) 273 | bpy.types.VIEW3D_MT_uv_map.remove(menu_start_planarProject) 274 | bpy.types.VIEW3D_MT_uv_map.remove(menu_start_copySymmetricUvs) 275 | bpy.types.VIEW3D_MT_uv_map.remove(menu_start_triplanarProject) 276 | 277 | #Unload icons 278 | for pcoll in preview_collections.values(): 279 | bpy.utils.previews.remove(pcoll) 280 | preview_collections.clear() 281 | 282 | if __name__ == "__main__": 283 | register() 284 | -------------------------------------------------------------------------------- /source/operators/vecmath.py: -------------------------------------------------------------------------------- 1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderUvTools). 2 | # Copyright (c) 2021 Mark McKay 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, version 3. 7 | # 8 | # This program is distributed in the hope that it will be useful, but 9 | # WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # 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, see . 15 | 16 | import mathutils 17 | import math 18 | from bpy_extras import view3d_utils 19 | from enum import Enum 20 | 21 | 22 | vecX = mathutils.Vector((1, 0, 0)) 23 | vecY = mathutils.Vector((0, 1, 0)) 24 | vecZ = mathutils.Vector((0, 0, 1)) 25 | vecZero = mathutils.Vector((0, 0, 0)) 26 | 27 | circleSegs = 64 28 | coordsCircle = [(math.sin(((2 * math.pi * i) / circleSegs)), math.cos((math.pi * 2 * i) / circleSegs), 0) for i in range(circleSegs + 1)] 29 | 30 | coordsSquare = [(0, 0, 0), (1, 0, 0), 31 | (1, 1, 0), (0, 1, 0) 32 | ] 33 | 34 | coordsSquare_strip = [(0, 0, 0), (1, 0, 0), 35 | (1, 1, 0), (0, 1, 0), 36 | (0, 0, 0) 37 | ] 38 | 39 | coordsSquare2_strip = [(-1, -1, 0), (1, -1, 0), 40 | (1, 1, 0), (-1, 1, 0), 41 | (-1, -1, 0) 42 | ] 43 | 44 | 45 | coordsCube = [(0, 0, 0), (1, 0, 0), 46 | (1, 0, 0), (1, 1, 0), 47 | (1, 1, 0), (0, 1, 0), 48 | (0, 1, 0), (0, 0, 0), 49 | 50 | (0, 0, 0), (0, 0, 1), 51 | (1, 0, 0), (1, 0, 1), 52 | (1, 1, 0), (1, 1, 1), 53 | (0, 1, 0), (0, 1, 1), 54 | 55 | (0, 0, 1), (1, 0, 1), 56 | (1, 0, 1), (1, 1, 1), 57 | (1, 1, 1), (0, 1, 1), 58 | (0, 1, 1), (0, 0, 1), 59 | ] 60 | 61 | cubeVerts = [(0, 0, 0), 62 | (1, 0, 0), 63 | (0, 1, 0), 64 | (1, 1, 0), 65 | (0, 0, 1), 66 | (1, 0, 1), 67 | (0, 1, 1), 68 | (1, 1, 1), 69 | ] 70 | 71 | cubeFaces = [(2, 3, 1, 0), 72 | (4, 5, 7, 6), 73 | (0, 1, 5, 4), 74 | (6, 7, 3, 2), 75 | (1, 3, 7, 5), 76 | (2, 0, 4, 6), 77 | ] 78 | 79 | cubeUvs = [ 80 | ((0, 0), (1, 0), (1, 1), (0, 1)), 81 | ((0, 0), (1, 0), (1, 1), (0, 1)), 82 | ((0, 0), (1, 0), (1, 1), (0, 1)), 83 | ((0, 0), (1, 0), (1, 1), (0, 1)), 84 | ((0, 0), (1, 0), (1, 1), (0, 1)), 85 | ((0, 0), (1, 0), (1, 1), (0, 1)) 86 | ] 87 | 88 | def unitCube(): 89 | coords = [] 90 | normals = [] 91 | uvs = [] 92 | 93 | v000 = mathutils.Vector((-1, -1, -1)) 94 | v100 = mathutils.Vector((1, -1, -1)) 95 | v010 = mathutils.Vector((-1, 1, -1)) 96 | v110 = mathutils.Vector((1, 1, -1)) 97 | v001 = mathutils.Vector((-1, -1, 1)) 98 | v101 = mathutils.Vector((1, -1, 1)) 99 | v011 = mathutils.Vector((-1, 1, 1)) 100 | v111 = mathutils.Vector((1, 1, 1)) 101 | 102 | nx0 = mathutils.Vector((-1, 0, 0)) 103 | nx1 = mathutils.Vector((1, 0, 0)) 104 | ny0 = mathutils.Vector((0, -1, 0)) 105 | ny1 = mathutils.Vector((0, 1, 0)) 106 | nz0 = mathutils.Vector((0, 0, -1)) 107 | nz1 = mathutils.Vector((0, 0, 1)) 108 | 109 | uv00 = mathutils.Vector((0, 0)) 110 | uv10 = mathutils.Vector((1, 0)) 111 | uv01 = mathutils.Vector((0, 1)) 112 | uv11 = mathutils.Vector((1, 1)) 113 | 114 | #Face -x 115 | coords.append(v010) 116 | coords.append(v000) 117 | coords.append(v001) 118 | 119 | coords.append(v010) 120 | coords.append(v001) 121 | coords.append(v011) 122 | 123 | for i in range(6): 124 | normals.append(nx0) 125 | 126 | uvs.append(uv00) 127 | uvs.append(uv10) 128 | uvs.append(uv11) 129 | uvs.append(uv00) 130 | uvs.append(uv11) 131 | uvs.append(uv01) 132 | 133 | 134 | #Face +x 135 | coords.append(v100) 136 | coords.append(v110) 137 | coords.append(v111) 138 | 139 | coords.append(v100) 140 | coords.append(v111) 141 | coords.append(v101) 142 | 143 | for i in range(6): 144 | normals.append(nx1) 145 | 146 | uvs.append(uv00) 147 | uvs.append(uv10) 148 | uvs.append(uv11) 149 | uvs.append(uv00) 150 | uvs.append(uv11) 151 | uvs.append(uv01) 152 | 153 | #Face -y 154 | coords.append(v000) 155 | coords.append(v100) 156 | coords.append(v101) 157 | 158 | coords.append(v000) 159 | coords.append(v101) 160 | coords.append(v001) 161 | 162 | for i in range(6): 163 | normals.append(ny0) 164 | 165 | uvs.append(uv00) 166 | uvs.append(uv10) 167 | uvs.append(uv11) 168 | uvs.append(uv00) 169 | uvs.append(uv11) 170 | uvs.append(uv01) 171 | 172 | 173 | #Face +y 174 | coords.append(v110) 175 | coords.append(v010) 176 | coords.append(v011) 177 | 178 | coords.append(v110) 179 | coords.append(v011) 180 | coords.append(v111) 181 | 182 | for i in range(6): 183 | normals.append(ny1) 184 | 185 | uvs.append(uv00) 186 | uvs.append(uv10) 187 | uvs.append(uv11) 188 | uvs.append(uv00) 189 | uvs.append(uv11) 190 | uvs.append(uv01) 191 | 192 | 193 | #Face -z 194 | coords.append(v010) 195 | coords.append(v110) 196 | coords.append(v100) 197 | 198 | coords.append(v010) 199 | coords.append(v100) 200 | coords.append(v000) 201 | 202 | for i in range(6): 203 | normals.append(nz0) 204 | 205 | uvs.append(uv00) 206 | uvs.append(uv10) 207 | uvs.append(uv11) 208 | uvs.append(uv00) 209 | uvs.append(uv11) 210 | uvs.append(uv01) 211 | 212 | 213 | #Face +z 214 | coords.append(v001) 215 | coords.append(v101) 216 | coords.append(v111) 217 | 218 | coords.append(v001) 219 | coords.append(v111) 220 | coords.append(v011) 221 | 222 | for i in range(6): 223 | normals.append(nz1) 224 | 225 | uvs.append(uv00) 226 | uvs.append(uv10) 227 | uvs.append(uv11) 228 | uvs.append(uv00) 229 | uvs.append(uv11) 230 | uvs.append(uv01) 231 | 232 | return (coords, normals, uvs) 233 | 234 | def unitCylinder(segs = 16, radius0 = 1, radius1 = 1, bottom_cap = False, top_cap = False): 235 | coords = [] 236 | normals = [] 237 | uvs = [] 238 | 239 | vc0 = mathutils.Vector((0, 0, -1)) 240 | vc1 = mathutils.Vector((0, 0, 1)) 241 | uvc = mathutils.Vector((.5, .5)) 242 | 243 | for s in range(segs): 244 | sin0 = math.sin(math.radians(360 * s / segs)) 245 | cos0 = math.cos(math.radians(360 * s / segs)) 246 | sin1 = math.sin(math.radians(360 * (s + 1) / segs)) 247 | cos1 = math.cos(math.radians(360 * (s + 1) / segs)) 248 | 249 | v00 = mathutils.Vector((sin0 * radius0, cos0 * radius0, -1)) 250 | v10 = mathutils.Vector((sin1 * radius0, cos1 * radius0, -1)) 251 | v01 = mathutils.Vector((sin0 * radius1, cos0 * radius1, 1)) 252 | v11 = mathutils.Vector((sin1 * radius1, cos1 * radius1, 1)) 253 | 254 | tan0 = mathutils.Vector((cos0, sin0, 0)) 255 | n00 = (v01 - v00).cross(tan0) 256 | n00.normalize() 257 | n01 = n00 258 | tan1 = mathutils.Vector((cos1, sin1, 0)) 259 | n10 = (v11 - v10).cross(tan1) 260 | n10.normalize() 261 | n11 = n10 262 | 263 | uv00 = mathutils.Vector((s / segs, 0)) 264 | uv10 = mathutils.Vector(((s + 1) / segs, 0)) 265 | uv01 = mathutils.Vector((s / segs, 1)) 266 | uv11 = mathutils.Vector(((s + 1) / segs, 1)) 267 | 268 | if radius0 != 0: 269 | coords.append(v00) 270 | coords.append(v10) 271 | coords.append(v11) 272 | 273 | normals.append(n00) 274 | normals.append(n10) 275 | normals.append(n11) 276 | 277 | uvs.append(uv00) 278 | uvs.append(uv10) 279 | uvs.append(uv11) 280 | 281 | if radius1 != 0: 282 | coords.append(v00) 283 | coords.append(v11) 284 | coords.append(v01) 285 | 286 | normals.append(n00) 287 | normals.append(n11) 288 | normals.append(n01) 289 | 290 | uvs.append(uv00) 291 | uvs.append(uv11) 292 | uvs.append(uv01) 293 | 294 | if top_cap and radius1 != 0: 295 | coords.append(v01) 296 | coords.append(v11) 297 | coords.append(vc1) 298 | 299 | normals.append(vecZ) 300 | normals.append(vecZ) 301 | normals.append(vecZ) 302 | 303 | uvs.append(mathutils.Vector((sin0, cos0))) 304 | uvs.append(mathutils.Vector((sin1, cos1))) 305 | uvs.append(uvc) 306 | 307 | if bottom_cap and radius0 != 0: 308 | coords.append(v00) 309 | coords.append(v10) 310 | coords.append(vc0) 311 | 312 | normals.append(-vecZ) 313 | normals.append(-vecZ) 314 | normals.append(-vecZ) 315 | 316 | uvs.append(mathutils.Vector((sin0, cos0))) 317 | uvs.append(mathutils.Vector((sin1, cos1))) 318 | uvs.append(uvc) 319 | 320 | 321 | return (coords, normals, uvs) 322 | 323 | 324 | def unitCone(segs = 16, radius = 1, cap = False): 325 | return unitCylinder(segs, radius, 0, cap, False) 326 | 327 | 328 | def unitSphere(segs_lat = 8, segs_long = 16): 329 | coords = [] 330 | normals = [] 331 | uvs = [] 332 | 333 | 334 | for la in range(segs_lat): 335 | z0 = math.cos(math.radians(180 * la / segs_lat)) 336 | z1 = math.cos(math.radians(180 * (la + 1) / segs_lat)) 337 | r0 = math.sin(math.radians(180 * la / segs_lat)) 338 | r1 = math.sin(math.radians(180 * (la + 1) / segs_lat)) 339 | 340 | for lo in range(segs_long): 341 | cx0 = math.sin(math.radians(360 * lo / segs_long)) 342 | cx1 = math.sin(math.radians(360 * (lo + 1) / segs_long)) 343 | cy0 = math.cos(math.radians(360 * lo / segs_long)) 344 | cy1 = math.cos(math.radians(360 * (lo + 1) / segs_long)) 345 | 346 | v00 = mathutils.Vector((cx0 * r0, cy0 * r0, z0)) 347 | v10 = mathutils.Vector((cx1 * r0, cy1 * r0, z0)) 348 | v01 = mathutils.Vector((cx0 * r1, cy0 * r1, z1)) 349 | v11 = mathutils.Vector((cx1 * r1, cy1 * r1, z1)) 350 | 351 | if la != 0: 352 | coords.append(v00) 353 | coords.append(v11) 354 | coords.append(v10) 355 | 356 | normals.append(v00) 357 | normals.append(v10) 358 | normals.append(v11) 359 | 360 | uvs.append((lo / segs_long, la / segs_lat)) 361 | uvs.append(((lo + 1) / segs_long, la / segs_lat)) 362 | uvs.append(((lo + 1) / segs_long, (la + 1) / segs_lat)) 363 | 364 | if la != segs_lat - 1: 365 | coords.append(v00) 366 | coords.append(v01) 367 | coords.append(v11) 368 | 369 | normals.append(v00) 370 | normals.append(v11) 371 | normals.append(v01) 372 | 373 | uvs.append((lo / segs_long, la / segs_lat)) 374 | uvs.append(((lo + 1) / segs_long, (la + 1) / segs_lat)) 375 | uvs.append((lo / segs_long, (la + 1) / segs_lat)) 376 | 377 | return (coords, normals, uvs) 378 | 379 | 380 | def unitTorus(radius = 1, ring_radius = .2, segs_u = 16, segs_v = 8): 381 | coords = [] 382 | normals = [] 383 | uvs = [] 384 | 385 | # print("--Build torus") 386 | 387 | for i in range(segs_u): 388 | cx0 = math.sin(math.radians(360 * i / segs_u)) * radius 389 | cy0 = math.cos(math.radians(360 * i / segs_u)) * radius 390 | cx1 = math.sin(math.radians(360 * (i + 1) / segs_u)) * radius 391 | cy1 = math.cos(math.radians(360 * (i + 1) / segs_u)) * radius 392 | 393 | c0 = mathutils.Vector((cx0, cy0, 0)) 394 | c1 = mathutils.Vector((cx1, cy1, 0)) 395 | 396 | # print("c0 %s" % (str(c0))) 397 | 398 | for j in range(segs_v): 399 | dir0 = c0 * ring_radius / c0.magnitude 400 | dir1 = c1 * ring_radius / c1.magnitude 401 | 402 | tan0 = dir0.cross(vecZ) 403 | tan1 = dir1.cross(vecZ) 404 | 405 | # print("dir0 %s" % (str(dir0))) 406 | # print("tan0 %s" % (str(tan0))) 407 | 408 | q00 = mathutils.Quaternion(tan0, math.radians(360 * j / segs_v)) 409 | q01 = mathutils.Quaternion(tan0, math.radians(360 * (j + 1) / segs_v)) 410 | q10 = mathutils.Quaternion(tan1, math.radians(360 * j / segs_v)) 411 | q11 = mathutils.Quaternion(tan1, math.radians(360 * (j + 1) / segs_v)) 412 | 413 | # m00 = q00.to_matrix() 414 | # m01 = q01.to_matrix() 415 | # m10 = q10.to_matrix() 416 | # m11 = q11.to_matrix() 417 | 418 | # print("m00 %s" % (str(m00))) 419 | 420 | # p00 = m00 @ dir0 + c0 421 | # p01 = m01 @ dir0 + c0 422 | # p10 = m10 @ dir1 + c1 423 | # p11 = m11 @ dir1 + c1 424 | 425 | # print("p00 %s" % (str(p00))) 426 | 427 | # p00 = q00 @ dir0 @ q00.conjugated() + c0 428 | # p01 = q01 @ dir0 @ q01.conjugated() + c0 429 | # p10 = q10 @ dir1 @ q10.conjugated() + c1 430 | # p11 = q11 @ dir1 @ q11.conjugated() + c1 431 | 432 | p00 = q00 @ dir0 + c0 433 | p01 = q01 @ dir0 + c0 434 | p10 = q10 @ dir1 + c1 435 | p11 = q11 @ dir1 + c1 436 | 437 | vu = p10 - p00 438 | vv = p01 - p00 439 | norm = vu.cross(vv) 440 | norm.normalize() 441 | 442 | uv00 = mathutils.Vector((i / segs_u, j / segs_v)) 443 | uv10 = mathutils.Vector(((i + 1) / segs_u, j / segs_v)) 444 | uv01 = mathutils.Vector((i / segs_u, (j + 1) / segs_v)) 445 | uv11 = mathutils.Vector(((i + 1) / segs_u, (j + 1) / segs_v)) 446 | 447 | coords.append(p00) 448 | coords.append(p10) 449 | coords.append(p11) 450 | 451 | coords.append(p00) 452 | coords.append(p11) 453 | coords.append(p01) 454 | 455 | for k in range(6): 456 | normals.append(norm) 457 | 458 | uvs.append(uv00) 459 | uvs.append(uv10) 460 | uvs.append(uv11) 461 | 462 | uvs.append(uv00) 463 | uvs.append(uv11) 464 | uvs.append(uv01) 465 | 466 | return (coords, normals, uvs) 467 | 468 | 469 | class Axis(Enum): 470 | X = 1 471 | Y = 2 472 | Z = 3 473 | 474 | 475 | class Face(Enum): 476 | X_POS = 0 477 | X_NEG = 1 478 | Y_POS = 2 479 | Y_NEG = 3 480 | Z_POS = 4 481 | Z_NEG = 5 482 | 483 | #Multiply a vector by a 4x4 matrix. Returns 3d vector. 484 | def mul_vector(matrix, vector): 485 | v0 = vector.to_4d() 486 | v0.w = 0 487 | v1 = matrix @ v0 488 | return v1.to_3d() 489 | 490 | 491 | 492 | 493 | #Returns the fraction of the viewport that a sphere of radius 1 will occupy 494 | def dist_from_viewport_center3(pos, region, rv3d): 495 | 496 | w2v = rv3d.view_matrix 497 | v2w = w2v.inverted() 498 | #view_origin = v2w.translation.copy() 499 | j = v2w.col[1].to_3d() 500 | 501 | # print("v2w " + str(v2w)) 502 | # print("j " + str(j)) 503 | 504 | persp = rv3d.perspective_matrix 505 | 506 | pos0_win = persp @ pos.to_4d() 507 | pos0_win /= pos0_win.w 508 | p0 = pos0_win.to_2d() 509 | 510 | # print("pos0_win " + str(pos0_win)) 511 | # print("p0 " + str(p0)) 512 | 513 | pos1_win = persp @ (pos + j).to_4d() 514 | pos1_win /= pos1_win.w 515 | p1 = pos1_win.to_2d() 516 | 517 | # print("pos1_win " + str(pos1_win)) 518 | # print("p1 " + str(p1)) 519 | 520 | dist = (p1 - p0).magnitude 521 | 522 | # print("dist " + str(dist)) 523 | 524 | # return dist / region.height 525 | # return 1 / dist 526 | # return region.height / dist 527 | return dist 528 | 529 | 530 | def calc_unit_scale3(pos, region, rv3d): 531 | 532 | w2win = rv3d.window_matrix @ rv3d.perspective_matrix @ rv3d.view_matrix 533 | 534 | p0 = pos.to_4d() 535 | p1 = (pos + vecZ).to_4d() 536 | 537 | q0 = w2win @ p0 538 | q1 = w2win @ p1 539 | 540 | q0 /= q0.w 541 | q1 /= q1.w 542 | 543 | dq = q1 - q0 544 | dq.z = 0 545 | 546 | print("p0 " + str(q0)) 547 | print("p1 " + str(q1)) 548 | print("dq " + str(dq)) 549 | 550 | return dq.magnitude 551 | 552 | 553 | #Returns scalar s to multiply line_dir by so that line_point + s * line_dir lies on plane 554 | # note that plane_norm does not need to be normalized 555 | def isect_line_plane(line_point, line_dir, plane_point, plane_norm): 556 | to_plane = (plane_point - line_point).project(plane_norm) 557 | dir_par_to_norm = line_dir.project(plane_norm) 558 | 559 | if dir_par_to_norm.magnitude == 0: 560 | return None 561 | 562 | scalar = to_plane.magnitude / dir_par_to_norm.magnitude 563 | if to_plane.dot(dir_par_to_norm) < 0: 564 | scalar = -scalar 565 | return scalar 566 | 567 | 568 | #Returns scalar s to multiply line_dir0 by so that line_point0 + s * line_dir0 is as close as possible to the other line 569 | def closest_point_to_line(line_point0, line_dir0, line_point1, line_dir1): 570 | #vector perpendicular to both line 0 and line 1 571 | r = line_dir0.cross(line_dir1) 572 | norm = r.cross(line_dir1) 573 | return isect_line_plane(line_point0, line_dir0, line_point1, norm) 574 | 575 | 576 | #Returns the ray of the intersection of two planes 577 | def isect_planes(point0, normal0, point1, normal1): 578 | ray_normal = normal0.cross(normal1) 579 | ray_normal.normalize() 580 | 581 | perp = ray_normal.cross(normal0) 582 | 583 | s = isect_line_plane(point0, perp, point1, normal1) 584 | ray_point = point0 + s * perp 585 | 586 | return ray_point, ray_normal 587 | 588 | 589 | #Finds the best s such that v1 = s * v0. Presumes vectors are parallel 590 | def findVectorScalar(v0, v1): 591 | xx = abs(v1.x - v0.x) 592 | yy = abs(v1.y - v0.y) 593 | zz = abs(v1.z - v0.z) 594 | 595 | if xx > yy and xx > zz: 596 | return v1.x / v0.x 597 | elif yy > zz: 598 | return v1.y / v0.y 599 | else: 600 | return z1.y / v0.z 601 | 602 | 603 | def abs_vector(vector): 604 | return mathutils.Vector((abs(vector.x), abs(vector.y), abs(vector.z))) 605 | 606 | def floor_vector(vector): 607 | return mathutils.Vector((math.floor(vector.x), math.floor(vector.y), math.floor(vector.z))) 608 | 609 | def mult_vector(matrix, vector): 610 | v = vector.copy() 611 | v.resize_4d() 612 | v.w = 0 613 | v = matrix @ v 614 | v.resize_3d() 615 | return v 616 | 617 | def mult_normal(matrix, normal): 618 | m = matrix.copy() 619 | m.invert() 620 | m.transpose() 621 | return mult_vector(m, normal) 622 | 623 | def closest_axis(vector): 624 | xx = abs(vector.x) 625 | yy = abs(vector.y) 626 | zz = abs(vector.z) 627 | 628 | if xx > yy and xx > zz: 629 | return Axis.X 630 | elif yy > zz: 631 | return Axis.Y 632 | else: 633 | return Axis.Z 634 | 635 | 636 | def project_point_onto_plane(point, plane_pt, plane_norm): 637 | proj = (point - plane_pt).project(plane_norm) 638 | return point - proj 639 | 640 | #return vector of coefficients [a, b, c] such that vec = a * v0 + b * v1 + c * v2 641 | def express_in_basis(vec, v0, v1, v2): 642 | v = mathutils.Matrix((v0, v1, v2)) #row order 643 | if v.determinant() == 0: 644 | return mathutils.Vector((0, 0, 0)) 645 | 646 | vI = v.copy() 647 | vI.transpose() 648 | vI.invert() 649 | return vI @ vec 650 | 651 | def snap_to_grid(pos, unit): 652 | p = mathutils.Vector(pos) 653 | p /= unit 654 | p += mathutils.Vector((.5, .5, .5)) 655 | 656 | p.x = math.floor(p.x) 657 | p.y = math.floor(p.y) 658 | p.z = math.floor(p.z) 659 | 660 | p *= unit 661 | 662 | return p 663 | 664 | def snap_to_grid_plane(pos, unit, plane_point, plane_normal): 665 | sp = snap_to_grid(pos, unit) 666 | 667 | axis = closest_axis(plane_normal) 668 | 669 | if axis == Axis.X: 670 | s = isect_line_plane(sp, vecX, plane_point, plane_normal) 671 | return sp + s * vecX 672 | elif axis == Axis.Y: 673 | s = isect_line_plane(sp, vecY, plane_point, plane_normal) 674 | return sp + s * vecY 675 | else: 676 | s = isect_line_plane(sp, vecZ, plane_point, plane_normal) 677 | return sp + s * vecZ 678 | 679 | def intersect_triangle(p0, p1, p2, pickOrigin, pickRay): 680 | v10 = p1 - p0 681 | v20 = p2 - p0 682 | v21 = p2 - p1 683 | norm = v10.cross(v20) 684 | norm.normalize() 685 | 686 | scalar = isect_line_plane(pickOrigin, pickRay, p0, norm) 687 | if scalar == None: 688 | return None 689 | 690 | hitPoint = pickOrigin + scalar * pickRay 691 | 692 | vh0 = hitPoint - p0 693 | vh1 = hitPoint - p1 694 | v01 = -v10 695 | 696 | if vh0.cross(v20).dot(v10.cross(v20)) < 0: 697 | return None 698 | if vh0.cross(v10).dot(v20.cross(v10)) < 0: 699 | return None 700 | if vh1.cross(v21).dot(v01.cross(v21)) < 0: 701 | return None 702 | 703 | return hitPoint 704 | 705 | 706 | 707 | 708 | class Bounds: 709 | def __init__(self, point): 710 | self.minBound = point.copy() 711 | self.maxBound = point.copy() 712 | 713 | def include_point(self, point): 714 | self.minBound.x = min(self.minBound.x, point.x) 715 | self.maxBound.x = max(self.maxBound.x, point.x) 716 | self.minBound.y = min(self.minBound.y, point.y) 717 | self.maxBound.y = max(self.maxBound.y, point.y) 718 | self.minBound.z = min(self.minBound.z, point.z) 719 | self.maxBound.z = max(self.maxBound.z, point.z) 720 | 721 | def include_bounds(self, bounds): 722 | include_point(bounds.minBound) 723 | include_point(bounds.maxBound) 724 | 725 | 726 | def mesh_bounds(obj, world = True, selected_faces_only = False): 727 | 728 | bounds = None 729 | 730 | # minCo = None 731 | # maxCo = None 732 | mesh = obj.data 733 | 734 | for p in mesh.polygons: 735 | if selected_faces_only and not p.select: 736 | continue 737 | 738 | for vIdx in p.vertices: 739 | v = mesh.vertices[vIdx] 740 | pos = mathutils.Vector(v.co) 741 | 742 | if world: 743 | pos = obj.matrix_world @ pos 744 | 745 | if bounds == None: 746 | bounds = Bounds(pos) 747 | else: 748 | bounds.include_point(pos) 749 | 750 | 751 | # for v in mesh.vertices: 752 | # pos = mathutils.Vector(v.co) 753 | # if world: 754 | # pos = obj.matrix_world @ pos 755 | 756 | # if bounds == None: 757 | # bounds = Bounds(pos) 758 | # else: 759 | # bounds.include_point(pos) 760 | 761 | 762 | return bounds 763 | 764 | 765 | 766 | def bmesh_bounds(obj, bmesh, world = True, selected_faces_only = False): 767 | 768 | bounds = None 769 | 770 | for f in bmesh.faces: 771 | if selected_faces_only and not p.select: 772 | continue 773 | 774 | for v in f.verts: 775 | pos = mathutils.Vector(v.co) 776 | if world: 777 | pos = obj.matrix_world @ pos 778 | 779 | if bounds == None: 780 | bounds = Bounds(pos) 781 | else: 782 | bounds.include_point(pos) 783 | 784 | 785 | # for v in bmesh.verts: 786 | # pos = mathutils.Vector(v.co) 787 | # if world: 788 | # pos = obj.matrix_world @ pos 789 | 790 | # # print("pos " + str(pos)) 791 | 792 | # if bounds == None: 793 | # bounds = Bounds(pos) 794 | # else: 795 | # bounds.include_point(pos) 796 | 797 | return bounds 798 | 799 | 800 | 801 | 802 | 803 | -------------------------------------------------------------------------------- /test/bar.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/test/bar.blend -------------------------------------------------------------------------------- /test/numpyTest.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/test/numpyTest.blend -------------------------------------------------------------------------------- /test/plane.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/test/plane.blend -------------------------------------------------------------------------------- /test/suzanne.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/test/suzanne.blend -------------------------------------------------------------------------------- /test/triangle.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blackears/blenderUvTools/545a229fcf9e229efe2b7214cf66317c964d485a/test/triangle.blend --------------------------------------------------------------------------------