├── .gitignore ├── LICENSE ├── README.md ├── __init__.py └── uv_squares.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UV Squares 2 | Blender's UV Editor tool that reshapes UV quad selection into a grid. 3 | 4 | ## Installation 5 | Go to `Edit > Preferences > Addons > Install` and either select .zip file or the unzipped `uv_squares.py` file. 6 | 7 | ## Location 8 | `UV Editor > N Panel > UV Squares` 9 | 10 | ## Support 11 | If you need help with the addon or you want to support me back please do so over BlenderMarket ❤️: 12 | https://blendermarket.com/products/uv-squares 13 | 14 | ## Affiliates 15 | If you are advertising the addon through a blog/course/video please contact me and I will give you a percent of the sales! 16 | 17 | ## Features 18 | * Reshape selected UV faces (quads) to **grid** of either: 19 | * equivalent **squares** (each square area is the same) 20 | * or by respect to **shape** of an active quad (area of rectangles can differ but they fit into straight lines) 21 | * convert multiple islands at once (select more than one separate UV chunk) 22 | * Align sequenced vertices on an **axis** (X or Y axis is determined by slope automatically): 23 | * make them **equally** distanced 24 | * Join selected faces/vertices to closest unselected vertices 25 | * Select single vertex and snap 2d cursor to it 26 | 27 | ## Shortcut 28 | * **Grid**/**Align**: **Alt + E** 29 | 30 | ## Notes 31 | **Aligning to axis** 32 | * All vertices have to be ordered/sequenced by x/y value depending of X/Y axis that they are getting aligned to. Otherwise you will have swapped vertices in the result. 33 | * What script does here: 34 | * set pivot to cursor (sets it back after) 35 | * 2d cursor will snap to closest vertex and the alignment will be made at that verts x/y value, depending on the axis 36 | * restrict scale to axis (recognize X or Y by the slope) 37 | * scale to 0 to where the cursor has snapped 38 | 39 | **Reshaping to grid** 40 | * Works on any UV selection shape of quad faces 41 | * You can specify an **active quad** by making it the last selected face. If not, one face will **automatically** be taken 42 | * 2d cursor is snapped to closest **corner** and is determining the direction for calculating the length of start and end of grid as well as **length** of one unit for square grid 43 | 44 | **Join vertices** 45 | * Snaps selected vertices to closest non selected 46 | * For faces, if you want to connect islands back to their original place: 47 | - use stitch (shortcut: Alt V, while stitching press I to toggle island) 48 | 49 | ## Development 50 | * When bumping versions increment both `bl_info` objects, one in `__init__.py` which is used for .zip install, and another in the main `uv_squares.py` file. -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) <2020> 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | bl_info = { 17 | "name": "UV Squares", 18 | "description": "UV Editor tool for reshaping quad selection to grid.", 19 | "author": "Reslav Hollos", 20 | "version": (1, 15, 0), 21 | "blender": (2, 80, 0), 22 | "location": "UV Editor > N Panel > UV Squares", 23 | "category": "UV", 24 | "wiki_url": "https://blendermarket.com/products/uv-squares" 25 | } 26 | 27 | from .uv_squares import * 28 | -------------------------------------------------------------------------------- /uv_squares.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) <2020> 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | bl_info = { 17 | "name": "UV Squares", 18 | "description": "UV Editor tool for reshaping quad selection to grid.", 19 | "author": "Reslav Hollos", 20 | "version": (1, 15, 0), 21 | "blender": (2, 80, 0), 22 | "location": "UV Editor > N Panel > UV Squares", 23 | "category": "UV", 24 | "wiki_url": "https://blendermarket.com/products/uv-squares" 25 | } 26 | 27 | import bpy 28 | import bmesh 29 | from collections import defaultdict 30 | from math import radians, hypot 31 | from timeit import default_timer as timer 32 | 33 | precision = 3 34 | 35 | #todo: make joining radius scale with editor zoom rate or average unit length 36 | #todo: align to axis by respect to vert distance 37 | #todo: snap 2dCursor to closest selected vert (when more vertices are selected 38 | #todo: rip different vertex on each press 39 | 40 | def main(context, operator, square = False, snapToClosest = False): 41 | if context.scene.tool_settings.use_uv_select_sync: 42 | operator.report({'ERROR'}, "Please disable 'Keep UV and edit mesh in sync'") 43 | # context.scene.tool_settings.use_uv_select_sync = False 44 | return 45 | 46 | selected_objects = context.selected_objects 47 | if (context.edit_object not in selected_objects): 48 | selected_objects.append(context.edit_object) 49 | 50 | for obj in selected_objects: 51 | if (obj.type == "MESH"): 52 | main1(obj, context, operator, square, snapToClosest) 53 | 54 | def main1(obj, context, operator, square, snapToClosest): 55 | if context.scene.tool_settings.use_uv_select_sync: 56 | operator.report({'ERROR'}, "Please disable 'Keep UV and edit mesh in sync'") 57 | # context.scene.tool_settings.use_uv_select_sync = False 58 | return 59 | 60 | startTime = timer() 61 | me = obj.data 62 | bm = bmesh.from_edit_mesh(me) 63 | uv_layer = bm.loops.layers.uv.verify() 64 | # bm.faces.layers.tex.verify() # currently blender needs both layers. 65 | 66 | edgeVerts, filteredVerts, selFaces, nonQuadFaces, vertsDict, noEdge = ListsOfVerts(uv_layer, bm) 67 | 68 | if len(filteredVerts) == 0: return 69 | if len(filteredVerts) == 1: 70 | SnapCursorToClosestSelected(filteredVerts) 71 | return 72 | 73 | cursorClosestTo = CursorClosestTo(filteredVerts) 74 | #line is selected 75 | 76 | if len(selFaces) == 0: 77 | if snapToClosest == True: 78 | SnapCursorToClosestSelected(filteredVerts) 79 | return 80 | 81 | VertsDictForLine(uv_layer, bm, filteredVerts, vertsDict) 82 | 83 | if AreVectsLinedOnAxis(filteredVerts) == False: 84 | ScaleTo0OnAxisAndCursor(filteredVerts, vertsDict, cursorClosestTo) 85 | return SuccessFinished(me, startTime) 86 | 87 | MakeEqualDistanceBetweenVertsInLine(filteredVerts, vertsDict, cursorClosestTo) 88 | return SuccessFinished(me, startTime) 89 | 90 | # deselect non quads 91 | for nf in nonQuadFaces: 92 | for l in nf.loops: 93 | luv = l[uv_layer] 94 | luv.select = False 95 | 96 | def isFaceSelected(f): 97 | return f.select and all(l[uv_layer].select for l in f.loops) 98 | 99 | def getIslandFromFace(startFace): 100 | island = set() 101 | toCheck = set([startFace]) 102 | 103 | while (len(toCheck)): 104 | face = toCheck.pop() 105 | if isFaceSelected(face) and face not in island: 106 | island.add(face) 107 | adjacentFaces = [] 108 | for e in face.edges: 109 | if e.seam == False: 110 | for f in e.link_faces: 111 | if f != face: 112 | adjacentFaces.append(f) 113 | toCheck.update(adjacentFaces) 114 | 115 | return island 116 | 117 | def getIslandsFromSelectedFaces(selectedFaces): 118 | islands = [] 119 | toCheck = set(selectedFaces) 120 | while(len(toCheck)): 121 | face = toCheck.pop() 122 | island = getIslandFromFace(face) 123 | islands.append(island) 124 | toCheck.difference_update(island) 125 | return islands 126 | 127 | islands = getIslandsFromSelectedFaces(selFaces) 128 | 129 | def main2 (targetFace, faces): 130 | ShapeFace(uv_layer, operator, targetFace, vertsDict, square) 131 | 132 | if square: FollowActiveUV(operator, me, targetFace, faces, 'EVEN') 133 | else: FollowActiveUV(operator, me, targetFace, faces) 134 | 135 | for island in islands: 136 | targetFace = bm.faces.active 137 | if (targetFace == None or 138 | targetFace not in island or 139 | len(islands) > 1 or 140 | targetFace.select == False or 141 | len(targetFace.verts) != 4): 142 | targetFace = next(iter(island)) 143 | 144 | main2(targetFace, island) 145 | 146 | if noEdge == False: 147 | #edge has ripped so we connect it back 148 | for ev in edgeVerts: 149 | key = (round(ev.uv.x, precision), round(ev.uv.y, precision)) 150 | if key in vertsDict: 151 | ev.uv = vertsDict[key][0].uv 152 | ev.select = True 153 | 154 | return SuccessFinished(me, startTime) 155 | 156 | '''def ScaleSelection(factor, pivot = 'CURSOR'): 157 | last_pivot = bpy.context.space_data.pivot_point 158 | bpy.context.space_data.pivot_point = pivot 159 | bpy.ops.transform.resize(value=(factor, factor, factor), constraint_axis=(False, False, False), mirror=False, proportional_edit_falloff='SMOOTH', proportional_size=1) 160 | bpy.context.space_data.pivot_point = last_pivot 161 | return''' 162 | 163 | def ShapeFace(uv_layer, operator, targetFace, vertsDict, square): 164 | corners = [] 165 | for l in targetFace.loops: 166 | luv = l[uv_layer] 167 | corners.append(luv) 168 | 169 | if len(corners) != 4: 170 | #operator.report({'ERROR'}, "bla") 171 | return 172 | 173 | lucv, ldcv, rucv, rdcv = Corners(corners) 174 | 175 | cct = CursorClosestTo([lucv, ldcv, rdcv, rucv]) 176 | MakeUvFaceEqualRectangle(vertsDict, lucv, rucv, rdcv, ldcv, cct, square) 177 | return 178 | 179 | def MakeUvFaceEqualRectangle(vertsDict, lucv, rucv, rdcv, ldcv, startv, square = False): 180 | sizeX, sizeY = ImageSize() 181 | ratio = sizeX/sizeY 182 | 183 | if startv == None: startv = lucv.uv 184 | elif AreVertsQuasiEqual(startv, rucv): startv = rucv.uv 185 | elif AreVertsQuasiEqual(startv, rdcv): startv = rdcv.uv 186 | elif AreVertsQuasiEqual(startv, ldcv): startv = ldcv.uv 187 | else: startv = lucv.uv 188 | 189 | lucv = lucv.uv 190 | rucv = rucv.uv 191 | rdcv = rdcv.uv 192 | ldcv = ldcv.uv 193 | 194 | if (startv == lucv): 195 | finalScaleX = hypotVert(lucv, rucv) 196 | finalScaleY = hypotVert(lucv, ldcv) 197 | currRowX = lucv.x 198 | currRowY = lucv.y 199 | 200 | elif (startv == rucv): 201 | finalScaleX = hypotVert(rucv, lucv) 202 | finalScaleY = hypotVert(rucv, rdcv) 203 | currRowX = rucv.x - finalScaleX 204 | currRowY = rucv.y 205 | 206 | elif (startv == rdcv): 207 | finalScaleX = hypotVert(rdcv, ldcv) 208 | finalScaleY = hypotVert(rdcv, rucv) 209 | currRowX = rdcv.x - finalScaleX 210 | currRowY = rdcv.y + finalScaleY 211 | 212 | else: 213 | finalScaleX = hypotVert(ldcv, rdcv) 214 | finalScaleY = hypotVert(ldcv, lucv) 215 | currRowX = ldcv.x 216 | currRowY = ldcv.y +finalScaleY 217 | 218 | if square: finalScaleY = finalScaleX*ratio 219 | #lucv, rucv 220 | x = round(lucv.x, precision) 221 | y = round(lucv.y, precision) 222 | for v in vertsDict[(x,y)]: 223 | v.uv.x = currRowX 224 | v.uv.y = currRowY 225 | 226 | x = round(rucv.x, precision) 227 | y = round(rucv.y, precision) 228 | for v in vertsDict[(x,y)]: 229 | v.uv.x = currRowX + finalScaleX 230 | v.uv.y = currRowY 231 | 232 | #rdcv, ldcv 233 | x = round(rdcv.x, precision) 234 | y = round(rdcv.y, precision) 235 | for v in vertsDict[(x,y)]: 236 | v.uv.x = currRowX + finalScaleX 237 | v.uv.y = currRowY - finalScaleY 238 | 239 | x = round(ldcv.x, precision) 240 | y = round(ldcv.y, precision) 241 | for v in vertsDict[(x,y)]: 242 | v.uv.x = currRowX 243 | v.uv.y = currRowY - finalScaleY 244 | 245 | 246 | return 247 | 248 | def SnapCursorToClosestSelected(filteredVerts): 249 | #TODO: snap to closest selected 250 | if len(filteredVerts) == 1: 251 | SetAll2dCursorsTo(filteredVerts[0].uv.x, filteredVerts[0].uv.y) 252 | 253 | return 254 | 255 | def ListsOfVerts(uv_layer, bm): 256 | edgeVerts = [] 257 | allEdgeVerts = [] 258 | filteredVerts = [] 259 | selFaces = [] 260 | nonQuadFaces = [] 261 | vertsDict = defaultdict(list) #dict 262 | 263 | for f in bm.faces: 264 | isFaceSel = True 265 | facesEdgeVerts = [] 266 | if (f.select == False): 267 | continue 268 | 269 | #collect edge verts if any 270 | for l in f.loops: 271 | luv = l[uv_layer] 272 | if luv.select == True: 273 | facesEdgeVerts.append(luv) 274 | else: isFaceSel = False 275 | 276 | allEdgeVerts.extend(facesEdgeVerts) 277 | if isFaceSel: 278 | if len(f.verts) != 4: 279 | nonQuadFaces.append(f) 280 | edgeVerts.extend(facesEdgeVerts) 281 | else: 282 | selFaces.append(f) 283 | 284 | for l in f.loops: 285 | luv = l[uv_layer] 286 | x = round(luv.uv.x, precision) 287 | y = round(luv.uv.y, precision) 288 | vertsDict[(x, y)].append(luv) 289 | 290 | else: edgeVerts.extend(facesEdgeVerts) 291 | 292 | noEdge = False 293 | if len(edgeVerts) == 0: 294 | noEdge = True 295 | edgeVerts.extend(allEdgeVerts) 296 | 297 | if len(selFaces) == 0: 298 | for ev in edgeVerts: 299 | if ListQuasiContainsVect(filteredVerts, ev) == False: 300 | filteredVerts.append(ev) 301 | else: filteredVerts = edgeVerts 302 | 303 | return edgeVerts, filteredVerts, selFaces, nonQuadFaces, vertsDict, noEdge 304 | 305 | def ListQuasiContainsVect(list, vect): 306 | for v in list: 307 | if AreVertsQuasiEqual(v, vect): 308 | return True 309 | return False 310 | 311 | #modified ideasman42's uvcalc_follow_active.py 312 | def FollowActiveUV(operator, me, f_act, faces, EXTEND_MODE = 'LENGTH_AVERAGE'): 313 | bm = bmesh.from_edit_mesh(me) 314 | uv_act = bm.loops.layers.uv.active 315 | 316 | # our own local walker 317 | def walk_face_init(faces, f_act): 318 | # first tag all faces True (so we dont uvmap them) 319 | for f in bm.faces: 320 | f.tag = True 321 | # then tag faces arg False 322 | for f in faces: 323 | f.tag = False 324 | # tag the active face True since we begin there 325 | f_act.tag = True 326 | 327 | def walk_face(f): 328 | # all faces in this list must be tagged 329 | f.tag = True 330 | faces_a = [f] 331 | faces_b = [] 332 | 333 | while faces_a: 334 | for f in faces_a: 335 | for l in f.loops: 336 | l_edge = l.edge 337 | if (l_edge.is_manifold == True) and (l_edge.seam == False): 338 | l_other = l.link_loop_radial_next 339 | f_other = l_other.face 340 | if not f_other.tag: 341 | yield (f, l, f_other) 342 | f_other.tag = True 343 | faces_b.append(f_other) 344 | # swap 345 | faces_a, faces_b = faces_b, faces_a 346 | faces_b.clear() 347 | 348 | def walk_edgeloop(l): 349 | """ 350 | Could make this a generic function 351 | """ 352 | e_first = l.edge 353 | e = None 354 | while True: 355 | e = l.edge 356 | yield e 357 | 358 | # don't step past non-manifold edges 359 | if e.is_manifold: 360 | # welk around the quad and then onto the next face 361 | l = l.link_loop_radial_next 362 | if len(l.face.verts) == 4: 363 | l = l.link_loop_next.link_loop_next 364 | if l.edge == e_first: 365 | break 366 | else: 367 | break 368 | else: 369 | break 370 | 371 | def extrapolate_uv(fac, 372 | l_a_outer, l_a_inner, 373 | l_b_outer, l_b_inner): 374 | l_b_inner[:] = l_a_inner 375 | l_b_outer[:] = l_a_inner + ((l_a_inner - l_a_outer) * fac) 376 | 377 | def apply_uv(f_prev, l_prev, f_next): 378 | l_a = [None, None, None, None] 379 | l_b = [None, None, None, None] 380 | 381 | l_a[0] = l_prev 382 | l_a[1] = l_a[0].link_loop_next 383 | l_a[2] = l_a[1].link_loop_next 384 | l_a[3] = l_a[2].link_loop_next 385 | 386 | # l_b 387 | # +-----------+ 388 | # |(3) |(2) 389 | # | | 390 | # |l_next(0) |(1) 391 | # +-----------+ 392 | # ^ 393 | # l_a | 394 | # +-----------+ 395 | # |l_prev(0) |(1) 396 | # | (f) | 397 | # |(3) |(2) 398 | # +-----------+ 399 | # copy from this face to the one above. 400 | 401 | # get the other loops 402 | l_next = l_prev.link_loop_radial_next 403 | if l_next.vert != l_prev.vert: 404 | l_b[1] = l_next 405 | l_b[0] = l_b[1].link_loop_next 406 | l_b[3] = l_b[0].link_loop_next 407 | l_b[2] = l_b[3].link_loop_next 408 | else: 409 | l_b[0] = l_next 410 | l_b[1] = l_b[0].link_loop_next 411 | l_b[2] = l_b[1].link_loop_next 412 | l_b[3] = l_b[2].link_loop_next 413 | 414 | l_a_uv = [l[uv_act].uv for l in l_a] 415 | l_b_uv = [l[uv_act].uv for l in l_b] 416 | 417 | if EXTEND_MODE == 'LENGTH_AVERAGE': 418 | try: 419 | fac = edge_lengths[l_b[2].edge.index][0] / edge_lengths[l_a[1].edge.index][0] 420 | except ZeroDivisionError: 421 | fac = 1.0 422 | elif EXTEND_MODE == 'LENGTH': 423 | a0, b0, c0 = l_a[3].vert.co, l_a[0].vert.co, l_b[3].vert.co 424 | a1, b1, c1 = l_a[2].vert.co, l_a[1].vert.co, l_b[2].vert.co 425 | 426 | d1 = (a0 - b0).length + (a1 - b1).length 427 | d2 = (b0 - c0).length + (b1 - c1).length 428 | try: 429 | fac = d2 / d1 430 | except ZeroDivisionError: 431 | fac = 1.0 432 | else: 433 | fac = 1.0 434 | 435 | extrapolate_uv(fac, 436 | l_a_uv[3], l_a_uv[0], 437 | l_b_uv[3], l_b_uv[0]) 438 | 439 | extrapolate_uv(fac, 440 | l_a_uv[2], l_a_uv[1], 441 | l_b_uv[2], l_b_uv[1]) 442 | 443 | # ------------------------------------------- 444 | # Calculate average length per loop if needed 445 | 446 | if EXTEND_MODE == 'LENGTH_AVERAGE': 447 | bm.edges.index_update() 448 | edge_lengths = [None] * len(bm.edges) #NoneType times the length of edges list 449 | 450 | for f in faces: 451 | # we know its a quad 452 | l_quad = f.loops[:] 453 | l_pair_a = (l_quad[0], l_quad[2]) 454 | l_pair_b = (l_quad[1], l_quad[3]) 455 | 456 | for l_pair in (l_pair_a, l_pair_b): 457 | if edge_lengths[l_pair[0].edge.index] == None: 458 | 459 | edge_length_store = [-1.0] 460 | edge_length_accum = 0.0 461 | edge_length_total = 0 462 | 463 | for l in l_pair: 464 | if edge_lengths[l.edge.index] == None: 465 | for e in walk_edgeloop(l): 466 | if edge_lengths[e.index] == None: 467 | edge_lengths[e.index] = edge_length_store 468 | edge_length_accum += e.calc_length() 469 | edge_length_total += 1 470 | 471 | edge_length_store[0] = edge_length_accum / edge_length_total 472 | 473 | # done with average length 474 | # ------------------------ 475 | 476 | walk_face_init(faces, f_act) 477 | for f_triple in walk_face(f_act): 478 | apply_uv(*f_triple) 479 | 480 | bmesh.update_edit_mesh(me, loop_triangles=False) 481 | 482 | '''----------------------------------''' 483 | 484 | def SuccessFinished(me, startTime): 485 | #use for backtrack of steps 486 | #bpy.ops.ed.undo_push() 487 | bmesh.update_edit_mesh(me) 488 | elapsed = round(timer()-startTime, 2) 489 | #if (elapsed >= 0.05): operator.report({'INFO'}, "UvSquares finished, elapsed:", elapsed, "s.") 490 | if (elapsed >= 0.05): print("UvSquares finished, elapsed:", elapsed, "s.") 491 | return 492 | 493 | '''def SymmetrySelected(axis, pivot = "MEDIAN"): 494 | last_pivot = bpy.context.space_data.pivot_point 495 | bpy.context.space_data.pivot_point = pivot 496 | bpy.ops.transform.mirror(constraint_axis=(True, False, False), constraint_orientation='GLOBAL', proportional_edit_falloff='SMOOTH', proportional_size=1) 497 | bpy.context.space_data.pivot_point = last_pivot 498 | return''' 499 | 500 | def AreVectsLinedOnAxis(verts): 501 | areLinedX = True 502 | areLinedY = True 503 | allowedError = 0.00001 504 | valX = verts[0].uv.x 505 | valY = verts[0].uv.y 506 | for v in verts: 507 | if abs(valX - v.uv.x) > allowedError: 508 | areLinedX = False 509 | if abs(valY - v.uv.y) > allowedError: 510 | areLinedY = False 511 | return areLinedX or areLinedY 512 | 513 | def MakeEqualDistanceBetweenVertsInLine(filteredVerts, vertsDict, startv = None): 514 | verts = filteredVerts 515 | verts.sort(key=lambda x: x.uv[0]) #sort by .x 516 | 517 | first = verts[0].uv 518 | last = verts[len(verts)-1].uv 519 | 520 | horizontal = True 521 | if ((last.x - first.x) >0.00001): 522 | slope = (last.y - first.y)/(last.x - first.x) 523 | if (slope > 1) or (slope <-1): 524 | horizontal = False 525 | else: 526 | horizontal = False 527 | 528 | if horizontal == True: 529 | length = hypot(first.x - last.x, first.y - last.y) 530 | 531 | if startv == last: 532 | currentX = last.x - length 533 | currentY = last.y 534 | else: 535 | currentX = first.x 536 | currentY = first.y 537 | else: 538 | verts.sort(key=lambda x: x.uv[1]) #sort by .y 539 | verts.reverse() #reverse because y values drop from up to down 540 | first = verts[0].uv 541 | last = verts[len(verts)-1].uv 542 | 543 | length = hypot(first.x - last.x, first.y - last.y) # we have to call length here because if it is not Hor first and second can not actually be first and second 544 | 545 | if startv == last: 546 | currentX = last.x 547 | currentY = last.y + length 548 | 549 | else: 550 | currentX = first.x 551 | currentY = first.y 552 | 553 | numberOfVerts = len(verts) 554 | finalScale = length / (numberOfVerts-1) 555 | 556 | if horizontal == True: 557 | first = verts[0] 558 | last = verts[len(verts)-1] 559 | 560 | for v in verts: 561 | v = v.uv 562 | x = round(v.x, precision) 563 | y = round(v.y, precision) 564 | 565 | for vert in vertsDict[(x,y)]: 566 | vert.uv.x = currentX 567 | vert.uv.y = currentY 568 | 569 | currentX = currentX + finalScale 570 | else: 571 | for v in verts: 572 | x = round(v.uv.x, precision) 573 | y = round(v.uv.y, precision) 574 | 575 | for vert in vertsDict[(x,y)]: 576 | vert.uv.x = currentX 577 | vert.uv.y = currentY 578 | 579 | currentY = currentY - finalScale 580 | return 581 | 582 | def VertsDictForLine(uv_layer, bm, selVerts, vertsDict): 583 | for f in bm.faces: 584 | for l in f.loops: 585 | luv = l[uv_layer] 586 | if luv.select == True: 587 | x = round(luv.uv.x, precision) 588 | y = round(luv.uv.y, precision) 589 | 590 | vertsDict[(x, y)].append(luv) 591 | return 592 | 593 | def ScaleTo0OnAxisAndCursor(filteredVerts, vertsDict, startv = None, horizontal = None): 594 | 595 | verts = filteredVerts 596 | verts.sort(key=lambda x: x.uv[0]) #sort by .x 597 | 598 | first = verts[0] 599 | last = verts[len(verts)-1] 600 | 601 | if horizontal == None: 602 | horizontal = True 603 | if ((last.uv.x - first.uv.x) >0.00001): 604 | slope = (last.uv.y - first.uv.y)/(last.uv.x - first.uv.x) 605 | if (slope > 1) or (slope <-1): 606 | horizontal = False 607 | else: 608 | horizontal = False 609 | 610 | if horizontal == True: 611 | if startv == None: 612 | startv = first 613 | 614 | SetAll2dCursorsTo(startv.uv.x, startv.uv.y) 615 | #scale to 0 on Y 616 | ScaleTo0('Y') 617 | return 618 | 619 | else: 620 | verts.sort(key=lambda x: x.uv[1]) #sort by .y 621 | verts.reverse() #reverse because y values drop from up to down 622 | first = verts[0] 623 | last = verts[len(verts)-1] 624 | if startv == None: 625 | startv = first 626 | 627 | SetAll2dCursorsTo(startv.uv.x, startv.uv.y) 628 | #scale to 0 on X 629 | ScaleTo0('X') 630 | return 631 | 632 | def ScaleTo0(axis): 633 | last_area = bpy.context.area.type 634 | bpy.context.area.type = 'IMAGE_EDITOR' 635 | last_pivot = bpy.context.space_data.pivot_point 636 | bpy.context.space_data.pivot_point = 'CURSOR' 637 | 638 | for area in bpy.context.screen.areas: 639 | if area.type == 'IMAGE_EDITOR': 640 | if axis == 'Y': 641 | bpy.ops.transform.resize(value=(1, 0, 1), constraint_axis=(False, True, False), mirror=False, proportional_edit_falloff='SMOOTH', proportional_size=1) 642 | else: 643 | bpy.ops.transform.resize(value=(0, 1, 1), constraint_axis=(True, False, False), mirror=False, proportional_edit_falloff='SMOOTH', proportional_size=1) 644 | 645 | 646 | bpy.context.space_data.pivot_point = last_pivot 647 | return 648 | 649 | 650 | def hypotVert(v1, v2): 651 | hyp = hypot(v1.x - v2.x, v1.y - v2.y) 652 | return hyp 653 | 654 | def Corners(corners): 655 | firstHighest = corners[0] 656 | for c in corners: 657 | if c.uv.y > firstHighest.uv.y: 658 | firstHighest = c 659 | corners.remove(firstHighest) 660 | 661 | secondHighest = corners[0] 662 | for c in corners: 663 | if (c.uv.y > secondHighest.uv.y): 664 | secondHighest = c 665 | 666 | if firstHighest.uv.x < secondHighest.uv.x: 667 | leftUp = firstHighest 668 | rightUp = secondHighest 669 | else: 670 | leftUp = secondHighest 671 | rightUp = firstHighest 672 | corners.remove(secondHighest) 673 | 674 | firstLowest = corners[0] 675 | secondLowest = corners[1] 676 | 677 | if firstLowest.uv.x < secondLowest.uv.x: 678 | leftDown = firstLowest 679 | rightDown = secondLowest 680 | else: 681 | leftDown = secondLowest 682 | rightDown = firstLowest 683 | 684 | return leftUp, leftDown, rightUp, rightDown 685 | 686 | def ImageSize(): 687 | ratioX, ratioY = 256,256 688 | for a in bpy.context.screen.areas: 689 | if a.type == 'IMAGE_EDITOR': 690 | img = a.spaces[0].image 691 | if img != None and img.size[0] != 0: 692 | ratioX, ratioY = img.size[0], img.size[1] 693 | break 694 | return ratioX, ratioY 695 | 696 | def CursorClosestTo(verts): 697 | sizeX, sizeY = ImageSize() 698 | if bpy.app.version >= (2, 80, 0): 699 | sizeX, sizeY = 1,1 700 | min = float('inf') 701 | minV = verts[0] 702 | for v in verts: 703 | if v == None: continue 704 | for area in bpy.context.screen.areas: 705 | if area.type == 'IMAGE_EDITOR': 706 | loc = area.spaces[0].cursor_location 707 | hyp = hypot(loc.x/sizeX -v.uv.x, loc.y/sizeY -v.uv.y) 708 | if (hyp < min): 709 | min = hyp 710 | minV = v 711 | return minV 712 | 713 | def SetAll2dCursorsTo(x,y): 714 | last_area = bpy.context.area.type 715 | bpy.context.area.type = 'IMAGE_EDITOR' 716 | 717 | bpy.ops.uv.cursor_set(location=(x, y)) 718 | 719 | bpy.context.area.type = last_area 720 | return 721 | 722 | '''def RotateSelected(angle, pivot = None): 723 | if pivot == None: 724 | pivot = "MEDIAN" 725 | 726 | last_area = bpy.context.area.type 727 | bpy.context.area.type = 'IMAGE_EDITOR' 728 | 729 | last_pivot = bpy.context.space_data.pivot_point 730 | bpy.context.space_data.pivot_point = pivot 731 | 732 | for area in bpy.context.screen.areas: 733 | if area.type == 'IMAGE_EDITOR': 734 | bpy.ops.transform.rotate(value=radians(angle), axis=(-0, -0, -1), constraint_axis=(False, False, False), constraint_orientation='LOCAL', mirror=False, proportional_edit_falloff='SMOOTH', proportional_size=1) 735 | break 736 | 737 | bpy.context.space_data.pivot_point = last_pivot 738 | bpy.context.area.type = last_area 739 | 740 | return''' 741 | 742 | def AreVertsQuasiEqual(v1, v2, allowedError = 0.00001): 743 | if abs(v1.uv.x -v2.uv.x) < allowedError and abs(v1.uv.y -v2.uv.y) < allowedError: 744 | return True 745 | return False 746 | 747 | def RipUvFaces(context, operator): 748 | startTime = timer() 749 | 750 | obj = context.active_object 751 | me = obj.data 752 | bm = bmesh.from_edit_mesh(me) 753 | 754 | uv_layer = bm.loops.layers.uv.verify() 755 | # bm.faces.layers.tex.verify() # currently blender needs both layers. 756 | 757 | selFaces = [] 758 | 759 | for f in bm.faces: 760 | isFaceSel = True 761 | for l in f.loops: 762 | luv = l[uv_layer] 763 | if luv.select == False: 764 | isFaceSel = False 765 | break 766 | 767 | if isFaceSel == True: 768 | selFaces.append(f) 769 | 770 | if len(selFaces) == 0: 771 | target = None 772 | for f in bm.faces: 773 | for l in f.loops: 774 | luv = l[uv_layer] 775 | if luv.select == True: 776 | target = luv 777 | break 778 | if target != None: break 779 | 780 | for f in bm.faces: 781 | for l in f.loops: 782 | luv = l[uv_layer] 783 | luv.select = False 784 | 785 | target.select = True 786 | return SuccessFinished(me, startTime) 787 | 788 | DeselectAll() 789 | 790 | for sf in selFaces: 791 | for l in sf.loops: 792 | luv = l[uv_layer] 793 | luv.select = True 794 | 795 | return SuccessFinished(me, startTime) 796 | 797 | def JoinUvFaces(context, operator): 798 | startTime = timer() 799 | 800 | obj = context.active_object 801 | me = obj.data 802 | bm = bmesh.from_edit_mesh(me) 803 | 804 | uv_layer = bm.loops.layers.uv.verify() 805 | # bm.faces.layers.tex.verify() # currently blender needs both layers. 806 | 807 | vertsDict = defaultdict(list) #dict 808 | 809 | #TODO: radius by image scale 810 | radius = 0.002 811 | 812 | for f in bm.faces: 813 | for l in f.loops: 814 | luv = l[uv_layer] 815 | if luv.select == True: 816 | x = round(luv.uv.x, precision) 817 | y = round(luv.uv.y, precision) 818 | vertsDict[(x,y)].append(luv) 819 | 820 | for key in vertsDict: 821 | min = 1 822 | minV = None 823 | 824 | for f in bm.faces: 825 | for l in f.loops: 826 | luv = l[uv_layer] 827 | if luv.select == False: 828 | hyp = hypot(vertsDict[(key[0], key[1])][0].uv.x -luv.uv.x, vertsDict[(key[0], key[1])][0].uv.y -luv.uv.y) 829 | if (hyp <= min) and hyp < radius: 830 | min = hyp 831 | minV = luv 832 | minV.select = True 833 | 834 | if min != 1: 835 | for v in vertsDict[(key[0], key[1])]: 836 | v = v.uv 837 | v.x = minV.uv.x 838 | v.y = minV.uv.y 839 | 840 | return SuccessFinished(me, startTime) 841 | 842 | def DeselectAll(): 843 | bpy.ops.uv.select_all(action='DESELECT') 844 | return 845 | 846 | 847 | class UV_PT_UvSquares(bpy.types.Operator): 848 | """Reshapes UV faces to a grid of equivalent squares""" 849 | bl_idname = "uv.uv_squares" 850 | bl_label = "UVs to grid of squares" 851 | bl_options = {'REGISTER', 'UNDO'} 852 | @classmethod 853 | def poll(cls, context): 854 | return (context.mode == 'EDIT_MESH') 855 | 856 | def execute(self, context): 857 | main(context, self, True) 858 | return {'FINISHED'} 859 | 860 | class UV_PT_UvSquaresByShape(bpy.types.Operator): 861 | """Reshapes UV faces to a grid with respect to shape by length of edges around selected corner""" 862 | bl_idname = "uv.uv_squares_by_shape" 863 | bl_label = "UVs to grid with respect to shape" 864 | bl_options = {'REGISTER', 'UNDO'} 865 | 866 | @classmethod 867 | def poll(cls, context): 868 | return (context.mode == 'EDIT_MESH') 869 | 870 | def execute(self, context): 871 | main(context, self) 872 | return {'FINISHED'} 873 | 874 | class UV_PT_RipFaces(bpy.types.Operator): 875 | """Rip UV faces apart""" 876 | bl_idname = "uv.uv_face_rip" 877 | bl_label = "UV face rip" 878 | bl_options = {'REGISTER', 'UNDO'} 879 | 880 | @classmethod 881 | def poll(cls, context): 882 | return (context.mode == 'EDIT_MESH') 883 | 884 | def execute(self, context): 885 | RipUvFaces(context, self) 886 | return {'FINISHED'} 887 | 888 | class UV_PT_JoinFaces(bpy.types.Operator): 889 | """Join selection to closest nonselected vertices (has to be very close)""" 890 | bl_idname = "uv.uv_face_join" 891 | bl_label = "UV selection join to closest unselected" 892 | bl_options = {'REGISTER', 'UNDO'} 893 | 894 | @classmethod 895 | def poll(cls, context): 896 | return (context.mode == 'EDIT_MESH') 897 | 898 | def execute(self, context): 899 | JoinUvFaces(context, self) 900 | return {'FINISHED'} 901 | 902 | class UV_PT_SnapToAxis(bpy.types.Operator): 903 | """Snap sequenced vertices to Axis""" 904 | bl_idname = "uv.uv_snap_to_axis" 905 | bl_label = "UV snap vertices to axis" 906 | bl_options = {'REGISTER', 'UNDO'} 907 | 908 | @classmethod 909 | def poll(cls, context): 910 | return (context.mode == 'EDIT_MESH') 911 | 912 | def execute(self, context): 913 | main(context, self) 914 | return {'FINISHED'} 915 | 916 | class UV_PT_SnapToAxisWithEqual(bpy.types.Operator): 917 | """Snap sequenced vertices to Axis with Equal Distance between""" 918 | bl_idname = "uv.uv_snap_to_axis_and_equal" 919 | bl_label = "UV snap vertices to axis with equal distance between" 920 | bl_options = {'REGISTER', 'UNDO'} 921 | 922 | @classmethod 923 | def poll(cls, context): 924 | return (context.mode == 'EDIT_MESH') 925 | 926 | def execute(self, context): 927 | main(context, self) 928 | main(context, self) 929 | return {'FINISHED'} 930 | 931 | addon_keymaps = [] 932 | 933 | def menu_func_uv_squares(self, context): self.layout.operator(UV_PT_UvSquares.bl_idname) 934 | def menu_func_uv_squares_by_shape(self, context): self.layout.operator(UV_PT_UvSquaresByShape.bl_idname) 935 | def menu_func_face_join(self, context): self.layout.operator(UV_PT_JoinFaces.bl_idname) 936 | 937 | class UV_PT_UvSquaresPanel(bpy.types.Panel): 938 | """UvSquares Panel""" 939 | bl_label = "UV Squares" 940 | bl_space_type = 'IMAGE_EDITOR' 941 | bl_region_type = 'UI' 942 | bl_category = 'UV Squares' 943 | 944 | def draw(self, context): 945 | layout = self.layout 946 | 947 | row = layout.row() 948 | row.label(text="Select Sequenced Vertices to:") 949 | split = layout.split() 950 | col = split.column(align=True) 951 | col.operator(UV_PT_SnapToAxis.bl_idname, text="Snap to Axis (X or Y)", icon = "ARROW_LEFTRIGHT") 952 | col.operator(UV_PT_SnapToAxisWithEqual.bl_idname, text="Snap with Equal Distance", icon = "THREE_DOTS") 953 | 954 | row = layout.row() 955 | row.label(text="Convert \"Rectangle\" (4 corners):") 956 | split = layout.split() 957 | col = split.column(align=True) 958 | col.operator(UV_PT_UvSquaresByShape.bl_idname, text="To Grid By Shape", icon = "UV_FACESEL") 959 | col.operator(UV_PT_UvSquares.bl_idname, text="To Square Grid", icon = "GRID") 960 | 961 | split = layout.split() 962 | col = split.column(align=True) 963 | row = col.row(align=True) 964 | 965 | row = layout.row() 966 | 967 | row.label(text="Select Faces or Vertices to:") 968 | split = layout.split() 969 | col = split.column(align=True) 970 | row = col.row(align=True) 971 | 972 | col.operator(UV_PT_JoinFaces.bl_idname, text="Snap to Closest Unselected", icon = "SNAP_GRID") 973 | row = layout.row() 974 | 975 | def register(): 976 | bpy.utils.register_class(UV_PT_UvSquaresPanel) 977 | bpy.utils.register_class(UV_PT_UvSquares) 978 | bpy.utils.register_class(UV_PT_UvSquaresByShape) 979 | bpy.utils.register_class(UV_PT_JoinFaces) 980 | bpy.utils.register_class(UV_PT_SnapToAxis) 981 | bpy.utils.register_class(UV_PT_SnapToAxisWithEqual) 982 | 983 | #menu 984 | bpy.types.IMAGE_MT_uvs.append(menu_func_uv_squares) 985 | bpy.types.IMAGE_MT_uvs.append(menu_func_uv_squares_by_shape) 986 | bpy.types.IMAGE_MT_uvs.append(menu_func_face_join) 987 | 988 | #handle the keymap 989 | wm = bpy.context.window_manager 990 | 991 | shortcut = {'key': 'E', 'alt': True, 'ctrl': False, 'shift': False} 992 | 993 | # TODO: skip adding if keymap already exists in UV Editor context 994 | if (wm.keyconfigs.addon): 995 | km = wm.keyconfigs.addon.keymaps.new(name='UV Editor', space_type='EMPTY') 996 | kmi = km.keymap_items.new(UV_PT_UvSquaresByShape.bl_idname, 997 | shortcut['key'], 'PRESS', alt=shortcut['alt'], ctrl=shortcut['ctrl'], shift=shortcut['shift']) 998 | addon_keymaps.append((km, kmi)) 999 | 1000 | def unregister(): 1001 | bpy.utils.unregister_class(UV_PT_UvSquaresPanel) 1002 | bpy.utils.unregister_class(UV_PT_UvSquares) 1003 | bpy.utils.unregister_class(UV_PT_UvSquaresByShape) 1004 | bpy.utils.unregister_class(UV_PT_JoinFaces) 1005 | bpy.utils.unregister_class(UV_PT_SnapToAxis) 1006 | bpy.utils.unregister_class(UV_PT_SnapToAxisWithEqual) 1007 | 1008 | bpy.types.IMAGE_MT_uvs.remove(menu_func_uv_squares) 1009 | bpy.types.IMAGE_MT_uvs.remove(menu_func_uv_squares_by_shape) 1010 | bpy.types.IMAGE_MT_uvs.remove(menu_func_face_join) 1011 | 1012 | # handle the keymap 1013 | for km, kmi in addon_keymaps: 1014 | km.keymap_items.remove(kmi) 1015 | # clear the list 1016 | addon_keymaps.clear() 1017 | 1018 | if __name__ == "__main__": 1019 | register() --------------------------------------------------------------------------------