├── .gitignore ├── LICENSE ├── README.md └── io_scene_wmo ├── __init__.py ├── addon_updater.py ├── addon_updater_ops.py ├── developer_utils.py ├── idproperty ├── idproperty.py └── ray_casting.py ├── m2 ├── import_m2.py ├── m2.py ├── skin.py └── wowfile.py ├── mpq ├── mpyq.py └── wow.py └── wmo ├── __init__.py ├── bsp_tree.py ├── collision.py ├── export_wmo.py ├── import_wmo.py ├── ui ├── __init__.py ├── enums.py ├── operators.py └── panels.py ├── wmo_file.py ├── wmo_format.py └── wmo_group.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | io_scene_wmo.sublime_project.sublime-project 64 | io_scene_wmo.sublime_project.sublime-workspace 65 | io_scene_wmo/io_scene_wmo.sublime-workspace 66 | io_scene_wmo/io_scene_wmo.sublime-project 67 | io_scene_wmo/bin/.vs/io_scene_wmo/v14/.suo 68 | io_scene_wmo/bin/io_scene_wmo.pyproj 69 | io_scene_wmo/bin/io_scene_wmo.sln 70 | io_scene_wmo/.vscode/launch.json 71 | .gitattributes 72 | .vs/io_scene_adt/v14/.suo 73 | io_scene_adt.sln 74 | io_scene_adt/.vs/io_scene_adt/v14/.suo 75 | io_scene_adt/__init__.py 76 | io_scene_adt/adt_format.py 77 | io_scene_adt/debug_utils.py 78 | io_scene_adt/developer_utils.py 79 | io_scene_adt/import_adt.py 80 | io_scene_adt/.vscode/launch.json 81 | io_scene_wmo/mpq/wow.py~RF3d9002.TMP 82 | io_scene_wmo/io_scene_wmo_updater/updater_status.json 83 | io_scene_wmo/io_wow_studio_updater/updater_status.json 84 | io_scene_wmo/.idea/workspace.xml 85 | io_scene_wmo/.idea/modules.xml 86 | io_scene_wmo/.idea/misc.xml 87 | io_scene_wmo/.idea/io_scene_wmo.iml 88 | .idea/workspace.xml 89 | .idea/wmo-addon-stable.iml 90 | .idea/misc.xml 91 | .idea/vcs.xml 92 | .idea/modules.xml 93 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | # Blender WMO import/export addon 2 | Actually this addon is much more than a usual import/export Blender plugin. Besides core functionality of importing and saving edited WMOs, this addon is also a powerful editor supporting nearly all features of World of Warcraft World Model Object (WMO) files. Written in Python using Blender API. 3 | 4 | # DEPRECATED!!! 5 | This repository is deprecated in favor of WoW Blender Studio, a more recent continuation of this addon. https://gitlab.com/skarnproject/blender-wow-studio. 6 | WoW Blender Studio is intended to be used with the most recent versions of Blender. The code on **this** repository only supports Blender 2.79b. No support for this version will be given. 7 | 8 | # What is World Model Object? 9 | World Model Object or just WMO is a special compound 3D structure used in the game World of Warcraft for making buildings, dungeons and other big complicated 3D objects. It does not only contain traditional 3D model parts as geometry, UV maps, materials and so on; but it does also support features like liquids, complex lighting system, portal culling system and much more. 10 | 11 | # WARNING: The code on this repo is work in progress 12 | This repo only exists for development purposes, not for deploying versions to users. File corruption may occur if you by chance pull some unfinished or broken code. The last "stable" verson is available on http://model-changing.net (Model Changing Network) and is supplied with how-to documentation. 13 | 14 | # Donation 15 | The provided software is available completely free of charge, however if you want to support me, here is my PayPal account: https://www.paypal.me/sergeishumakov2015 16 | 17 | # Currently supported features 18 | - Geometry editing. The script allows the user to edit WMO geometry, UVmaps and create outdoor and indor groups. 19 | - Material editing. The addon supports all features of WoW material system. A user is able to create materials, set textures, change used shaders, blending modes, flags etc. 20 | - Vertex colors. 21 | - WMO portals. The script addon supports all features of WMO portals, except antiportal creation. 22 | - WMO fogs. 23 | - WMO liquids. The liquid system is fully supported including UV editing for lava and tile flags. 24 | - Collision. 25 | - Render batches. 26 | - Lightmaps. 27 | - Quick WMO panel. A UI interface aimed to ease the process of WMO creation. 28 | 29 | # Credits 30 | Developers: 31 | - happyhack (original addon version) 32 | - Miton (portals and other contributions) 33 | - Skarn (current developer) 34 | - Supora (initial vertex color import/export support) 35 | - p620 (multiple help with complicated coding tasks) 36 | 37 | Testers: 38 | - Balkron 39 | - Amaroth 40 | - Supora 41 | - Kadzhamit 42 | - gratural 43 | - Vellear 44 | - intra 45 | & others. 46 | 47 | Special thanks to Deamon and fallenoak for information on batches and portals and all other http://wowdev.wiki contributors. 48 | 49 | # Planned features 50 | - Transport convex volume planes 51 | - Doodadset editing. (If the m2 plugin arrives by that time) 52 | 53 | # Installation and usage: 54 | http://www.model-changing.net/files/file/56-wmo-importexport-blender-scripts-updated-25022016/ (relevant to last officially released version) 55 | -------------------------------------------------------------------------------- /io_scene_wmo/__init__.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | # 20 | 21 | 22 | bl_info = { 23 | "name": "Wow WMO format (.wmo)", 24 | "author": "Happyhack, Skarn", 25 | "version": (2, 0), 26 | "blender": (2, 78, 0), 27 | "location": "File > Import-Export > WoW WMO (.wmo) ", 28 | "description": "Import-Export WoW WMO", 29 | "warning": "", 30 | "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/" 31 | "Scripts/Import-Export/Wow_WMO_IO", 32 | "tracker_url": "https://developer.blender.org/T25692", 33 | "category": "Import-Export"} 34 | 35 | # load and reload submodules 36 | ################################## 37 | 38 | import importlib 39 | 40 | import bpy 41 | from bpy.props import StringProperty, BoolProperty 42 | from bpy_extras.io_utils import ExportHelper 43 | 44 | from .wmo.ui import enums 45 | from .wmo.ui import operators 46 | from .wmo.ui import panels 47 | from . import addon_updater_ops 48 | from .idproperty import idproperty 49 | from .mpq import wow as mpq 50 | from .wmo import export_wmo 51 | from .wmo import import_wmo 52 | from .wmo import wmo_file 53 | from .wmo import wmo_group 54 | 55 | importlib.reload(wmo_file) 56 | importlib.reload(wmo_group) 57 | importlib.reload(import_wmo) 58 | importlib.reload(export_wmo) 59 | importlib.reload(enums) 60 | importlib.reload(operators) 61 | importlib.reload(panels) 62 | importlib.reload(mpq) 63 | 64 | class WMOPreferences(bpy.types.AddonPreferences): 65 | bl_idname = __package__ 66 | 67 | wow_path = StringProperty( 68 | name="WoW Client Path", 69 | subtype='DIR_PATH' 70 | ) 71 | 72 | fileinfo_path = StringProperty( 73 | name="Path to fileinfo.exe", 74 | subtype='FILE_PATH' 75 | ) 76 | 77 | wmv_path = StringProperty( 78 | name="WoW Model Viewer Log Path", 79 | subtype='FILE_PATH' 80 | ) 81 | 82 | blp_path = StringProperty( 83 | name="BLP Converter Path", 84 | subtype='FILE_PATH' 85 | ) 86 | 87 | # addon updater preferences 88 | 89 | auto_check_update = bpy.props.BoolProperty( 90 | name = "Auto-check for Update", 91 | description = "If enabled, auto-check for updates using an interval", 92 | default = True, 93 | ) 94 | 95 | updater_intrval_months = bpy.props.IntProperty( 96 | name='Months', 97 | description = "Number of months between checking for updates", 98 | default=0, 99 | min=0 100 | ) 101 | updater_intrval_days = bpy.props.IntProperty( 102 | name='Days', 103 | description = "Number of days between checking for updates", 104 | default=7, 105 | min=0, 106 | ) 107 | updater_intrval_hours = bpy.props.IntProperty( 108 | name='Hours', 109 | description = "Number of hours between checking for updates", 110 | default=0, 111 | min=0, 112 | max=23 113 | ) 114 | updater_intrval_minutes = bpy.props.IntProperty( 115 | name='Minutes', 116 | description = "Number of minutes between checking for updates", 117 | default=0, 118 | min=0, 119 | max=59 120 | ) 121 | 122 | def draw(self, context): 123 | self.layout.prop(self, "wow_path") 124 | self.layout.prop(self, "wmv_path") 125 | self.layout.prop(self, "blp_path") 126 | self.layout.prop(self, "fileinfo_path") 127 | addon_updater_ops.update_settings_ui(self, context) 128 | 129 | class WMOImporter(bpy.types.Operator): 130 | """Load WMO mesh data""" 131 | bl_idname = "import_mesh.wmo" 132 | bl_label = "Import WMO" 133 | bl_options = {'UNDO'} 134 | 135 | filepath = StringProperty( 136 | subtype='FILE_PATH', 137 | ) 138 | 139 | filter_glob = StringProperty( 140 | default="*.wmo", 141 | options={'HIDDEN'} 142 | ) 143 | 144 | load_textures = BoolProperty( 145 | name="Fetch textures", 146 | description="Automatically fetch textures from game data", 147 | default=True, 148 | ) 149 | 150 | import_doodads = BoolProperty( 151 | name="Import doodad sets", 152 | description="Import WMO doodad set to scene", 153 | default=True, 154 | ) 155 | 156 | group_objects = BoolProperty( 157 | name="Group objects", 158 | description="Group all objects of this WMO on import", 159 | default=False, 160 | ) 161 | 162 | def execute(self, context): 163 | import_wmo.import_wmo_to_blender_scene(self.filepath, self.load_textures, self.import_doodads, self.group_objects) 164 | return {'FINISHED'} 165 | 166 | def invoke(self, context, event): 167 | wm = context.window_manager 168 | wm.fileselect_add(self) 169 | return {'RUNNING_MODAL'} 170 | 171 | 172 | class WMOExporter(bpy.types.Operator, ExportHelper): 173 | """Save WMO mesh data""" 174 | bl_idname = "export_mesh.wmo" 175 | bl_label = "Export WMO" 176 | bl_options = {'PRESET'} 177 | 178 | filename_ext = ".wmo" 179 | 180 | filter_glob = StringProperty( 181 | default="*.wmo", 182 | options={'HIDDEN'} 183 | ) 184 | 185 | export_selected = BoolProperty( 186 | name="Export selected objects", 187 | description="Makes the exporter export only selected objects on the scene", 188 | default=False, 189 | ) 190 | 191 | autofill_textures = BoolProperty( 192 | name="Fill texture paths", 193 | description="Automatically fills WoW Material texture paths based on texture filenames", 194 | default=True, 195 | ) 196 | 197 | 198 | def execute(self, context): 199 | export_wmo.export_wmo_from_blender_scene(self.filepath, self.autofill_textures, self.export_selected) 200 | 201 | return {'FINISHED'} 202 | 203 | 204 | def menu_import(self, context): 205 | self.layout.operator(WMOImporter.bl_idname, text="Wow WMO (.wmo)") 206 | 207 | 208 | def menu_export(self, context): 209 | self.layout.operator(WMOExporter.bl_idname, text="Wow WMO (.wmo)") 210 | 211 | 212 | def register(): 213 | addon_updater_ops.register(bl_info) 214 | idproperty.register() 215 | bpy.utils.register_module(__name__) 216 | panels.register() 217 | bpy.types.INFO_MT_file_import.append(menu_import) 218 | bpy.types.INFO_MT_file_export.append(menu_export) 219 | 220 | 221 | def unregister(): 222 | bpy.utils.unregister_module(__name__) 223 | panels.unregister() 224 | bpy.types.INFO_MT_file_import.remove(menu_import) 225 | bpy.types.INFO_MT_file_export.remove(menu_export) 226 | idproperty.unregister() 227 | 228 | if __name__ == "__main__": 229 | register() -------------------------------------------------------------------------------- /io_scene_wmo/addon_updater_ops.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # This program is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU General Public License 5 | # as published by the Free Software Foundation; either version 2 6 | # of the License, or (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program; if not, write to the Free Software Foundation, 15 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | 19 | import bpy 20 | from bpy.app.handlers import persistent 21 | import os 22 | 23 | # updater import, import safely 24 | try: 25 | from .addon_updater import Updater as updater 26 | except Exception as e: 27 | print("ERROR INITIALIZING UPDATER") 28 | print(str(e)) 29 | class Singleton_updater_none(object): 30 | def __init__(self): 31 | self.addon = None 32 | self.verbose = False 33 | self.invalidupdater = True # used to distinguish bad install 34 | self.error = None 35 | self.error_msg = None 36 | self.async_checking = None 37 | updater = Singleton_updater_none() 38 | updater.error = "Error initializing updater module" 39 | updater.error_msg = str(e) 40 | 41 | # Must declare this before classes are loaded 42 | # otherwise the bl_idname's will not match and have errors. 43 | # Must be all lowercase and no spaces 44 | updater.addon = "io_scene_wmo" 45 | 46 | # ----------------------------------------------------------------------------- 47 | # Updater operators 48 | # ----------------------------------------------------------------------------- 49 | 50 | 51 | # simple popup for prompting checking for update & allow to install if available 52 | class addon_updater_install_popup(bpy.types.Operator): 53 | """Check and install update if available""" 54 | bl_label = "Update {x} addon".format(x=updater.addon) 55 | bl_idname = updater.addon+".updater_install_popup" 56 | bl_description = "Popup menu to check and display current updates available" 57 | 58 | def invoke(self, context, event): 59 | return context.window_manager.invoke_props_dialog(self) 60 | 61 | def draw(self, context): 62 | layout = self.layout 63 | if updater.invalidupdater == True: 64 | layout.label("Updater module error") 65 | return 66 | if updater.update_ready == True: 67 | col = layout.column() 68 | col.scale_y = 0.7 69 | col.label("Update ready! Press OK to install "\ 70 | +str(updater.update_version)) 71 | col.label("or click outside window to defer") 72 | # could offer to remove popups here, but window will not redraw 73 | # so may be confusing to the user/look like a bug 74 | # row = layout.row() 75 | # row.label("Prevent future popups:") 76 | # row.operator(addon_updater_ignore.bl_idname,text="Ignore update") 77 | elif updater.update_ready == False: 78 | col = layout.column() 79 | col.scale_y = 0.7 80 | col.label("No updates available") 81 | col.label("Press okay to dismiss dialog") 82 | # add option to force install 83 | else: 84 | # case: updater.update_ready = None 85 | # we have not yet checked for the update 86 | layout.label("Check for update now?") 87 | 88 | # potentially in future, could have UI for 'check to select old version' 89 | # to revert back to. 90 | 91 | def execute(self,context): 92 | 93 | # in case of error importing updater 94 | if updater.invalidupdater == True: 95 | return {'CANCELLED'} 96 | 97 | if updater.manual_only==True: 98 | row.operator("wm.url_open",text="Open website").url=\ 99 | updater.website 100 | elif updater.update_ready == True: 101 | res = updater.run_update(force=False, callback=post_update_callback) 102 | # should return 0, if not something happened 103 | if updater.verbose: 104 | if res==0: print("Updater returned successful") 105 | else: print("Updater returned "+str(res)+", error occurred") 106 | elif updater.update_ready is None: 107 | (update_ready, version, link) = updater.check_for_update(now=True) 108 | 109 | # re-launch this dialog 110 | atr = addon_updater_install_popup.bl_idname.split(".") 111 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 112 | else: 113 | if updater.verbose:print("Doing nothing, not ready for update") 114 | return {'FINISHED'} 115 | 116 | 117 | # User preference check-now operator 118 | class addon_updater_check_now(bpy.types.Operator): 119 | bl_label = "Check now for "+updater.addon+" update" 120 | bl_idname = updater.addon+".updater_check_now" 121 | bl_description = "Check now for an update to the {x} addon".format( 122 | x=updater.addon) 123 | 124 | def execute(self,context): 125 | 126 | # in case of error importing updater 127 | if updater.invalidupdater == True: 128 | return {'CANCELLED'} 129 | 130 | if updater.async_checking == True and updater.error is None: 131 | # Check already happened 132 | # Used here to just avoid constant applying settings below 133 | # Ignoring if error, to prevent being stuck on the error screen 134 | return {'CANCELLED'} 135 | return 136 | 137 | # apply the UI settings 138 | settings = context.user_preferences.addons[__package__].preferences 139 | updater.set_check_interval(enable=settings.auto_check_update, 140 | months=settings.updater_intrval_months, 141 | days=settings.updater_intrval_days, 142 | hours=settings.updater_intrval_hours, 143 | minutes=settings.updater_intrval_minutes 144 | ) # optional, if auto_check_update 145 | 146 | # input is an optional callback function 147 | # this function should take a bool input, if true: update ready 148 | # if false, no update ready 149 | updater.check_for_update_now() 150 | 151 | return {'FINISHED'} 152 | 153 | class addon_updater_update_now(bpy.types.Operator): 154 | bl_label = "Update "+updater.addon+" addon now" 155 | bl_idname = updater.addon+".updater_update_now" 156 | bl_description = "Update to the latest version of the {x} addon".format( 157 | x=updater.addon) 158 | 159 | 160 | def execute(self,context): 161 | 162 | # in case of error importing updater 163 | if updater.invalidupdater == True: 164 | return {'CANCELLED'} 165 | 166 | if updater.manual_only == True: 167 | row.operator("wm.url_open",text="Open website").url=\ 168 | updater.website 169 | if updater.update_ready == True: 170 | # if it fails, offer to open the website instead 171 | try: 172 | res = updater.run_update( 173 | force=False, 174 | callback=post_update_callback) 175 | 176 | # should return 0, if not something happened 177 | if updater.verbose: 178 | if res==0: print("Updater returned successful") 179 | else: print("Updater returned "+str(res)+", error occurred") 180 | except: 181 | atr = addon_updater_install_manually.bl_idname.split(".") 182 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 183 | elif updater.update_ready is None: 184 | (update_ready, version, link) = updater.check_for_update(now=True) 185 | # re-launch this dialog 186 | atr = addon_updater_install_popup.bl_idname.split(".") 187 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 188 | 189 | elif updater.update_ready == False: 190 | self.report({'INFO'}, "Nothing to update") 191 | else: 192 | self.report({'ERROR'}, "Encountered problem while trying to update") 193 | 194 | return {'FINISHED'} 195 | 196 | 197 | class addon_updater_update_target(bpy.types.Operator): 198 | bl_label = updater.addon+" addon version target" 199 | bl_idname = updater.addon+".updater_update_target" 200 | bl_description = "Install a targeted version of the {x} addon".format( 201 | x=updater.addon) 202 | 203 | def target_version(self, context): 204 | # in case of error importing updater 205 | if updater.invalidupdater == True: 206 | ret = [] 207 | 208 | ret = [] 209 | i=0 210 | for tag in updater.tags: 211 | ret.append( (tag,tag,"Select to install "+tag) ) 212 | i+=1 213 | return ret 214 | 215 | target = bpy.props.EnumProperty( 216 | name="Target version", 217 | description="Select the version to install", 218 | items=target_version 219 | ) 220 | 221 | @classmethod 222 | def poll(cls, context): 223 | if updater.invalidupdater == True: return False 224 | return updater.update_ready is not None and len(updater.tags) > 0 225 | 226 | def invoke(self, context, event): 227 | return context.window_manager.invoke_props_dialog(self) 228 | 229 | def draw(self, context): 230 | layout = self.layout 231 | if updater.invalidupdater == True: 232 | layout.label("Updater error") 233 | return 234 | split = layout.split(percentage=0.66) 235 | subcol = split.column() 236 | subcol.label("Select install version") 237 | subcol = split.column() 238 | subcol.prop(self, "target", text="") 239 | 240 | 241 | def execute(self,context): 242 | 243 | # in case of error importing updater 244 | if updater.invalidupdater == True: 245 | return {'CANCELLED'} 246 | 247 | res = updater.run_update( 248 | force=False, 249 | revert_tag=self.target, 250 | callback=post_update_callback) 251 | 252 | # should return 0, if not something happened 253 | if updater.verbose: 254 | if res==0: print("Updater returned successful") 255 | else: print("Updater returned "+str(res)+", error occurred") 256 | return {'CANCELLED'} 257 | # try: 258 | # updater.run_update(force=False,revert_tag=self.target) 259 | # except: 260 | # self.report({'ERROR'}, "Problem installing target version") 261 | 262 | return {'FINISHED'} 263 | 264 | 265 | class addon_updater_install_manually(bpy.types.Operator): 266 | """As a fallback, direct the user to download the addon manually""" 267 | bl_label = "Install update manually" 268 | bl_idname = updater.addon+".updater_install_manually" 269 | bl_description = "Proceed to manually install update" 270 | 271 | def invoke(self, context, event): 272 | return context.window_manager.invoke_popup(self) 273 | 274 | def draw(self, context): 275 | layout = self.layout 276 | 277 | if updater.invalidupdater == True: 278 | layout.label("Updater error") 279 | return 280 | 281 | # use a "failed flag"? it shows this label if the case failed. 282 | if False: 283 | layout.label("There was an issue trying to auto-install") 284 | else: 285 | col = layout.column() 286 | col.scale_y = 0.7 287 | col.label("Install the addon manually") 288 | col.label("Press the download button below and install") 289 | col.label("the zip file like a normal addon.") 290 | 291 | # if check hasn't happened, ie accidentally called this menu 292 | # allow to check here 293 | 294 | row = layout.row() 295 | 296 | if updater.update_link is not None: 297 | row.operator("wm.url_open",text="Direct download").url=\ 298 | updater.update_link 299 | else: 300 | row.operator("wm.url_open",text="(failed to retrieve)") 301 | row.enabled = False 302 | 303 | if updater.website is not None: 304 | row = layout.row() 305 | row.operator("wm.url_open",text="Open website").url=\ 306 | updater.website 307 | else: 308 | row = layout.row() 309 | row.label("See source website to download the update") 310 | 311 | def execute(self,context): 312 | 313 | return {'FINISHED'} 314 | 315 | 316 | class addon_updater_updated_successful(bpy.types.Operator): 317 | """Addon in place, popup telling user it completed""" 318 | bl_label = "Success" 319 | bl_idname = updater.addon+".updater_update_successful" 320 | bl_description = "Update installation was successful" 321 | bl_options = {'REGISTER', 'UNDO'} 322 | 323 | def invoke(self, context, event): 324 | return context.window_manager.invoke_props_popup(self, event) 325 | 326 | def draw(self, context): 327 | layout = self.layout 328 | 329 | if updater.invalidupdater == True: 330 | layout.label("Updater error") 331 | return 332 | 333 | # use a "failed flag"? it show this label if the case failed. 334 | saved = updater.json 335 | if updater.auto_reload_post_update == False: 336 | # tell user to restart blender 337 | if "just_restored" in saved and saved["just_restored"] == True: 338 | col = layout.column() 339 | col.scale_y = 0.7 340 | col.label("Addon restored") 341 | col.label("Restart blender to reload.") 342 | updater.json_reset_restore() 343 | else: 344 | col = layout.column() 345 | col.scale_y = 0.7 346 | col.label("Addon successfully installed") 347 | col.label("Restart blender to reload.") 348 | 349 | else: 350 | # reload addon, but still recommend they restart blender 351 | if "just_restored" in saved and saved["just_restored"] == True: 352 | col = layout.column() 353 | col.scale_y = 0.7 354 | col.label("Addon restored") 355 | col.label("Consider restarting blender to fully reload.") 356 | updater.json_reset_restore() 357 | else: 358 | col = layout.column() 359 | col.scale_y = 0.7 360 | col.label("Addon successfully installed.") 361 | col.label("Consider restarting blender to fully reload.") 362 | 363 | def execut(self, context): 364 | return {'FINISHED'} 365 | 366 | 367 | class addon_updater_restore_backup(bpy.types.Operator): 368 | """Restore addon from backup""" 369 | bl_label = "Restore backup" 370 | bl_idname = updater.addon+".updater_restore_backup" 371 | bl_description = "Restore addon from backup" 372 | 373 | @classmethod 374 | def poll(cls, context): 375 | try: 376 | return os.path.isdir(os.path.join(updater.stage_path,"backup")) 377 | except: 378 | return False 379 | 380 | def execute(self, context): 381 | # in case of error importing updater 382 | if updater.invalidupdater == True: 383 | return {'CANCELLED'} 384 | updater.restore_backup() 385 | return {'FINISHED'} 386 | 387 | 388 | class addon_updater_ignore(bpy.types.Operator): 389 | """Prevent future update notice popups""" 390 | bl_label = "Ignore update" 391 | bl_idname = updater.addon+".updater_ignore" 392 | bl_description = "Ignore update to prevent future popups" 393 | 394 | @classmethod 395 | def poll(cls, context): 396 | if updater.invalidupdater == True: 397 | return False 398 | elif updater.update_ready == True: 399 | return True 400 | else: 401 | return False 402 | 403 | def execute(self, context): 404 | # in case of error importing updater 405 | if updater.invalidupdater == True: 406 | return {'CANCELLED'} 407 | updater.ignore_update() 408 | self.report({"INFO"},"Open addon preferences for updater options") 409 | return {'FINISHED'} 410 | 411 | 412 | class addon_updater_end_background(bpy.types.Operator): 413 | """Stop checking for update in the background""" 414 | bl_label = "End background check" 415 | bl_idname = updater.addon+".end_background_check" 416 | bl_description = "Stop checking for update in the background" 417 | 418 | # @classmethod 419 | # def poll(cls, context): 420 | # if updater.async_checking == True: 421 | # return True 422 | # else: 423 | # return False 424 | 425 | def execute(self, context): 426 | # in case of error importing updater 427 | if updater.invalidupdater == True: 428 | return {'CANCELLED'} 429 | updater.stop_async_check_update() 430 | return {'FINISHED'} 431 | 432 | 433 | # ----------------------------------------------------------------------------- 434 | # Handler related, to create popups 435 | # ----------------------------------------------------------------------------- 436 | 437 | 438 | # global vars used to prevent duplicate popup handlers 439 | ran_autocheck_install_popup = False 440 | ran_update_sucess_popup = False 441 | 442 | # global var for preventing successive calls 443 | ran_background_check = False 444 | 445 | @persistent 446 | def updater_run_success_popup_handler(scene): 447 | global ran_update_sucess_popup 448 | ran_update_sucess_popup = True 449 | 450 | # in case of error importing updater 451 | if updater.invalidupdater == True: 452 | return 453 | 454 | try: 455 | bpy.app.handlers.scene_update_post.remove( 456 | updater_run_success_popup_handler) 457 | except: 458 | pass 459 | 460 | atr = addon_updater_updated_successful.bl_idname.split(".") 461 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 462 | 463 | 464 | @persistent 465 | def updater_run_install_popup_handler(scene): 466 | global ran_autocheck_install_popup 467 | ran_autocheck_install_popup = True 468 | 469 | # in case of error importing updater 470 | if updater.invalidupdater == True: 471 | return 472 | 473 | try: 474 | bpy.app.handlers.scene_update_post.remove( 475 | updater_run_install_popup_handler) 476 | except: 477 | pass 478 | 479 | if "ignore" in updater.json and updater.json["ignore"] == True: 480 | return # don't do popup if ignore pressed 481 | elif type(updater.update_version) != type((0,0,0)): 482 | # likely was from master or another branch, shouldn't trigger popup 483 | updater.json_reset_restore() 484 | return 485 | elif "version_text" in updater.json and "version" in updater.json["version_text"]: 486 | version = updater.json["version_text"]["version"] 487 | ver_tuple = updater.version_tuple_from_text(version) 488 | 489 | if ver_tuple < updater.current_version: 490 | # user probably manually installed to get the up to date addon 491 | # in here. Clear out the update flag using this function 492 | if updater.verbose: 493 | print("{} updater: appears user updated, clearing flag".format(\ 494 | updater.addon)) 495 | updater.json_reset_restore() 496 | return 497 | atr = addon_updater_install_popup.bl_idname.split(".") 498 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 499 | 500 | 501 | # passed into the updater, background thread updater 502 | def background_update_callback(update_ready): 503 | global ran_autocheck_install_popup 504 | 505 | # in case of error importing updater 506 | if updater.invalidupdater == True: 507 | return 508 | 509 | if update_ready != True: 510 | return 511 | 512 | if updater_run_install_popup_handler not in \ 513 | bpy.app.handlers.scene_update_post and \ 514 | ran_autocheck_install_popup==False: 515 | bpy.app.handlers.scene_update_post.append( 516 | updater_run_install_popup_handler) 517 | 518 | ran_autocheck_install_popup = True 519 | 520 | 521 | # a callback for once the updater has completed 522 | # Only makes sense to use this if "auto_reload_post_update" == False, 523 | # ie don't auto-restart the addon 524 | def post_update_callback(): 525 | 526 | # in case of error importing updater 527 | if updater.invalidupdater == True: 528 | return 529 | 530 | # this is the same code as in conditional at the end of the register function 531 | # ie if "auto_reload_post_update" == True, comment out this code 532 | if updater.verbose: print("{} updater: Running post update callback".format(updater.addon)) 533 | #bpy.app.handlers.scene_update_post.append(updater_run_success_popup_handler) 534 | 535 | atr = addon_updater_updated_successful.bl_idname.split(".") 536 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 537 | global ran_update_sucess_popup 538 | ran_update_sucess_popup = True 539 | return 540 | 541 | 542 | # function for asynchronous background check, which *could* be called on register 543 | def check_for_update_background(context): 544 | 545 | # in case of error importing updater 546 | if updater.invalidupdater == True: 547 | return 548 | 549 | global ran_background_check 550 | if ran_background_check == True: 551 | # Global var ensures check only happens once 552 | return 553 | elif updater.update_ready is not None or updater.async_checking == True: 554 | # Check already happened 555 | # Used here to just avoid constant applying settings below 556 | return 557 | 558 | # apply the UI settings 559 | settings = context.user_preferences.addons[__package__].preferences 560 | updater.set_check_interval(enable=settings.auto_check_update, 561 | months=settings.updater_intrval_months, 562 | days=settings.updater_intrval_days, 563 | hours=settings.updater_intrval_hours, 564 | minutes=settings.updater_intrval_minutes 565 | ) # optional, if auto_check_update 566 | 567 | # input is an optional callback function 568 | # this function should take a bool input, if true: update ready 569 | # if false, no update ready 570 | if updater.verbose: 571 | print("{} updater: Running background check for update".format(\ 572 | updater.addon)) 573 | updater.check_for_update_async(background_update_callback) 574 | ran_background_check = True 575 | 576 | 577 | # can be placed in front of other operators to launch when pressed 578 | def check_for_update_nonthreaded(self, context): 579 | 580 | # in case of error importing updater 581 | if updater.invalidupdater == True: 582 | return 583 | 584 | # only check if it's ready, ie after the time interval specified 585 | # should be the async wrapper call here 586 | 587 | settings = context.user_preferences.addons[__package__].preferences 588 | updater.set_check_interval(enable=settings.auto_check_update, 589 | months=settings.updater_intrval_months, 590 | days=settings.updater_intrval_days, 591 | hours=settings.updater_intrval_hours, 592 | minutes=settings.updater_intrval_minutes 593 | ) # optional, if auto_check_update 594 | 595 | (update_ready, version, link) = updater.check_for_update(now=False) 596 | if update_ready == True: 597 | atr = addon_updater_install_popup.bl_idname.split(".") 598 | getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') 599 | else: 600 | if updater.verbose: print("No update ready") 601 | self.report({'INFO'}, "No update ready") 602 | 603 | # for use in register only, to show popup after re-enabling the addon 604 | # must be enabled by developer 605 | def showReloadPopup(): 606 | 607 | # in case of error importing updater 608 | if updater.invalidupdater == True: 609 | return 610 | 611 | saved_state = updater.json 612 | global ran_update_sucess_popup 613 | 614 | a = saved_state is not None 615 | b = "just_updated" in saved_state 616 | c = saved_state["just_updated"] 617 | 618 | if a and b and c: 619 | updater.json_reset_postupdate() # so this only runs once 620 | 621 | # no handlers in this case 622 | if updater.auto_reload_post_update == False: return 623 | 624 | if updater_run_success_popup_handler not in \ 625 | bpy.app.handlers.scene_update_post \ 626 | and ran_update_sucess_popup==False: 627 | bpy.app.handlers.scene_update_post.append( 628 | updater_run_success_popup_handler) 629 | ran_update_sucess_popup = True 630 | 631 | 632 | # ----------------------------------------------------------------------------- 633 | # Example UI integrations 634 | # ----------------------------------------------------------------------------- 635 | 636 | 637 | # UI to place e.g. at the end of a UI panel where to notify update available 638 | def update_notice_box_ui(self, context): 639 | 640 | # in case of error importing updater 641 | if updater.invalidupdater == True: 642 | return 643 | 644 | saved_state = updater.json 645 | if updater.auto_reload_post_update == False: 646 | if "just_updated" in saved_state and saved_state["just_updated"] == True: 647 | layout = self.layout 648 | box = layout.box() 649 | col = box.column() 650 | col.scale_y = 0.7 651 | col.label("Restart blender", icon="ERROR") 652 | col.label("to complete update") 653 | return 654 | 655 | # if user pressed ignore, don't draw the box 656 | if "ignore" in updater.json and updater.json["ignore"] == True: 657 | return 658 | 659 | if updater.update_ready != True: return 660 | 661 | settings = context.user_preferences.addons[__package__].preferences 662 | layout = self.layout 663 | box = layout.box() 664 | col = box.column(align=True) 665 | 666 | if updater.manual_only==False: 667 | col.label("Update ready!",icon="ERROR") 668 | col.operator("wm.url_open", text="Open website").url = updater.website 669 | #col.operator("wm.url_open",text="Direct download").url=updater.update_link 670 | col.operator(addon_updater_install_manually.bl_idname, "Install manually") 671 | col.operator(addon_updater_update_now.bl_idname, 672 | "Update now", icon="LOOP_FORWARDS") 673 | else: 674 | col.operator("wm.url_open", text="Get update", icon="ERROR").url = \ 675 | updater.website 676 | col.operator(addon_updater_ignore.bl_idname,icon="X") 677 | 678 | 679 | 680 | # create a function that can be run inside user preferences panel for prefs UI 681 | # place inside UI draw using: addon_updater_ops.updaterSettingsUI(self, context) 682 | # or by: addon_updater_ops.updaterSettingsUI(context) 683 | def update_settings_ui(self, context): 684 | 685 | layout = self.layout 686 | box = layout.box() 687 | 688 | # in case of error importing updater 689 | if updater.invalidupdater == True: 690 | box.label("Error initializing updater code:") 691 | box.label(updater.error_msg) 692 | return 693 | 694 | settings = context.user_preferences.addons[__package__].preferences 695 | 696 | # auto-update settings 697 | box.label("Updater Settings") 698 | row = box.row() 699 | 700 | # special case to tell user to restart blender, if set that way 701 | if updater.auto_reload_post_update == False: 702 | saved_state = updater.json 703 | if "just_updated" in saved_state and saved_state["just_updated"] == True: 704 | row.label("Restart blender to complete update", icon="ERROR") 705 | return 706 | 707 | split = row.split(percentage=0.3) 708 | subcol = split.column() 709 | subcol.prop(settings, "auto_check_update") 710 | subcol = split.column() 711 | 712 | if settings.auto_check_update==False: subcol.enabled = False 713 | subrow = subcol.row() 714 | subrow.label("Interval between checks") 715 | subrow = subcol.row(align=True) 716 | checkcol = subrow.column(align=True) 717 | checkcol.prop(settings,"updater_intrval_months") 718 | checkcol = subrow.column(align=True) 719 | checkcol.prop(settings,"updater_intrval_days") 720 | checkcol = subrow.column(align=True) 721 | checkcol.prop(settings,"updater_intrval_hours") 722 | checkcol = subrow.column(align=True) 723 | checkcol.prop(settings,"updater_intrval_minutes") 724 | 725 | 726 | # checking / managing updates 727 | row = box.row() 728 | col = row.column() 729 | movemosue = False 730 | if updater.error is not None: 731 | subcol = col.row(align=True) 732 | subcol.scale_y = 1 733 | split = subcol.split(align=True) 734 | split.enabled = False 735 | split.scale_y = 2 736 | split.operator(addon_updater_check_now.bl_idname, 737 | updater.error) 738 | split = subcol.split(align=True) 739 | split.scale_y = 2 740 | split.operator(addon_updater_check_now.bl_idname, 741 | text = "", icon="FILE_REFRESH") 742 | 743 | elif updater.update_ready is None and updater.async_checking == False: 744 | col.scale_y = 2 745 | col.operator(addon_updater_check_now.bl_idname) 746 | elif updater.update_ready is None: # async is running 747 | subcol = col.row(align=True) 748 | subcol.scale_y = 1 749 | split = subcol.split(align=True) 750 | split.enabled = False 751 | split.scale_y = 2 752 | split.operator(addon_updater_check_now.bl_idname, 753 | "Checking...") 754 | split = subcol.split(align=True) 755 | split.scale_y = 2 756 | split.operator(addon_updater_end_background.bl_idname, 757 | text = "", icon="X") 758 | 759 | elif updater.include_branches==True and \ 760 | len(updater.tags)==len(updater.include_branch_list) and \ 761 | updater.manual_only==False: 762 | # no releases found, but still show the appropriate branch 763 | subcol = col.row(align=True) 764 | subcol.scale_y = 1 765 | split = subcol.split(align=True) 766 | split.scale_y = 2 767 | split.operator(addon_updater_update_now.bl_idname, 768 | "Update directly to "+str(updater.include_branch_list[0])) 769 | split = subcol.split(align=True) 770 | split.scale_y = 2 771 | split.operator(addon_updater_check_now.bl_idname, 772 | text = "", icon="FILE_REFRESH") 773 | 774 | elif updater.update_ready==True and updater.manual_only==False: 775 | subcol = col.row(align=True) 776 | subcol.scale_y = 1 777 | split = subcol.split(align=True) 778 | split.scale_y = 2 779 | split.operator(addon_updater_update_now.bl_idname, 780 | "Update now to "+str(updater.update_version)) 781 | split = subcol.split(align=True) 782 | split.scale_y = 2 783 | split.operator(addon_updater_check_now.bl_idname, 784 | text = "", icon="FILE_REFRESH") 785 | 786 | elif updater.update_ready==True and updater.manual_only==True: 787 | col.scale_y = 2 788 | col.operator("wm.url_open", 789 | "Download "+str(updater.update_version)).url=updater.website 790 | else: # ie that updater.update_ready == False 791 | subcol = col.row(align=True) 792 | subcol.scale_y = 1 793 | split = subcol.split(align=True) 794 | split.enabled = False 795 | split.scale_y = 2 796 | split.operator(addon_updater_check_now.bl_idname, 797 | "Addon is up to date") 798 | split = subcol.split(align=True) 799 | split.scale_y = 2 800 | split.operator(addon_updater_check_now.bl_idname, 801 | text = "", icon="FILE_REFRESH") 802 | 803 | if updater.manual_only == False: 804 | col = row.column(align=True) 805 | #col.operator(addon_updater_update_target.bl_idname, 806 | if updater.include_branches == True and len(updater.include_branch_list)>0: 807 | branch = updater.include_branch_list[0] 808 | col.operator(addon_updater_update_target.bl_idname, 809 | "Install latest {} / old version".format(branch)) 810 | else: 811 | col.operator(addon_updater_update_target.bl_idname, 812 | "Reinstall / install old version") 813 | lastdate = "none found" 814 | backuppath = os.path.join(updater.stage_path,"backup") 815 | if "backup_date" in updater.json and os.path.isdir(backuppath): 816 | if updater.json["backup_date"] == "": 817 | lastdate = "Date not found" 818 | else: 819 | lastdate = updater.json["backup_date"] 820 | backuptext = "Restore addon backup ({})".format(lastdate) 821 | col.operator(addon_updater_restore_backup.bl_idname, backuptext) 822 | 823 | row = box.row() 824 | row.scale_y = 0.7 825 | lastcheck = updater.json["last_check"] 826 | if updater.error is not None and updater.error_msg is not None: 827 | row.label(updater.error_msg) 828 | elif movemosue == True: 829 | row.label("Move mouse if button doesn't update") 830 | elif lastcheck != "" and lastcheck is not None: 831 | lastcheck = lastcheck[0: lastcheck.index(".") ] 832 | row.label("Last update check: " + lastcheck) 833 | else: 834 | row.label("Last update check: None") 835 | 836 | 837 | # a global function for tag skipping 838 | # a way to filter which tags are displayed, 839 | # e.g. to limit downgrading too far 840 | # input is a tag text, e.g. "v1.2.3" 841 | # output is True for skipping this tag number, 842 | # False if the tag is allowed (default for all) 843 | def skip_tag_function(tag): 844 | 845 | # in case of error importing updater 846 | if updater.invalidupdater == True: 847 | return False 848 | 849 | # ---- write any custom code here, return true to disallow version ---- # 850 | # 851 | # # Filter out e.g. if 'beta' is in name of release 852 | # if 'beta' in tag.lower(): 853 | # return True 854 | # ---- write any custom code above, return true to disallow version --- # 855 | 856 | if updater.include_branches == True: 857 | for branch in updater.include_branch_list: 858 | if tag["name"].lower() == branch: return False 859 | 860 | # function converting string to tuple, ignoring e.g. leading 'v' 861 | tupled = updater.version_tuple_from_text(tag["name"]) 862 | if type(tupled) != type( (1,2,3) ): return True 863 | 864 | # select the min tag version - change tuple accordingly 865 | if updater.version_min_update is not None: 866 | if tupled < updater.version_min_update: 867 | return True # skip if current version below this 868 | 869 | # select the max tag version 870 | if updater.version_max_update is not None: 871 | if tupled >= updater.version_max_update: 872 | return True # skip if current version at or above this 873 | 874 | # in all other cases, allow showing the tag for updating/reverting 875 | return False 876 | 877 | 878 | # ----------------------------------------------------------------------------- 879 | # Register, should be run in the register module itself 880 | # ----------------------------------------------------------------------------- 881 | 882 | 883 | # registering the operators in this module 884 | def register(bl_info): 885 | 886 | # See output to verify this register function is working properly 887 | # print("Running updater reg") 888 | 889 | # choose your own username 890 | updater.user = "WowDevTools" 891 | 892 | # choose your own repository, must match github name 893 | updater.repo = "Blender-WMO-import-export-scripts" 894 | 895 | #updater.addon = # define at top of module, MUST be done first 896 | 897 | # Website for manual addon download, optional but reocmmended to set 898 | updater.website = "http://www.model-changing.net/files/file/56-wmo-importexport-blender-scripts/" 899 | 900 | # used to check/compare versions 901 | updater.current_version = bl_info["version"] 902 | 903 | # to hard-set update frequency, use this here - however, this demo 904 | # has this set via UI properties. Optional 905 | # updater.set_check_interval( 906 | # enable=False,months=0,days=0,hours=0,minutes=2) 907 | 908 | # Optional, consider turning off for production or allow as an option 909 | # This will print out additional debugging info to the console 910 | updater.verbose = False # make False for production default 911 | 912 | # Optional, customize where the addon updater processing subfolder is, 913 | # essentially a staging folder used by the updater on its own 914 | # Needs to be within the same folder as the addon itself 915 | # updater.updater_path = # set path of updater folder, by default: 916 | # /addons/{__package__}/{__package__}_updater 917 | 918 | # auto create a backup of the addon when installing other versions 919 | updater.backup_current = True # True by default 920 | 921 | # Allow branches like 'master' as an option to update to, regardless 922 | # of release or version. 923 | # Default behavior: releases will still be used for auto check (popup), 924 | # but the user has the option from user preferences to directly 925 | # update to the master branch or any other branches specified using 926 | # the "install {branch}/older version" operator. 927 | updater.include_branches = True 928 | 929 | # if using "include_branches", 930 | # updater.include_branch_list defaults to ['master'] branch if set to none 931 | # example targeting another multiple branches allowed to pull from 932 | # updater.include_branch_list = ['master', 'dev'] # example with two branches 933 | updater.include_branch_list = None # is the equvalent to setting ['master'] 934 | 935 | # Only allow manual install, thus prompting the user to open 936 | # the addon's webpage to download, specifically: updater.website 937 | # Useful if only wanting to get notification of updates but not 938 | # directly install. 939 | updater.manual_only = False 940 | 941 | # Used for development only, "pretend" to install an update to test 942 | # reloading conditions 943 | updater.fake_install = False # Set to true to test callback/reloading 944 | 945 | # Override with a custom function on what tags 946 | # to skip showing for updater; see code for function above. 947 | # Set the min and max versions allowed to install. 948 | # Optional, default None 949 | # min install (>=) will install this and higher 950 | updater.version_min_update = (0,0,0) 951 | # updater.version_min_update = None # if not wanting to define a min 952 | 953 | # max install (<) will install strictly anything lower 954 | # updater.version_max_update = (9,9,9) 955 | updater.version_max_update = None # if not wanting to define a max 956 | 957 | updater.skip_tag = skip_tag_function # min and max used in this function 958 | 959 | # The register line items for all operators/panels 960 | # If using bpy.utils.register_module(__name__) to register elsewhere 961 | # in the addon, delete these lines (also from unregister) 962 | bpy.utils.register_class(addon_updater_install_popup) 963 | bpy.utils.register_class(addon_updater_check_now) 964 | bpy.utils.register_class(addon_updater_update_now) 965 | bpy.utils.register_class(addon_updater_update_target) 966 | bpy.utils.register_class(addon_updater_install_manually) 967 | bpy.utils.register_class(addon_updater_updated_successful) 968 | bpy.utils.register_class(addon_updater_restore_backup) 969 | bpy.utils.register_class(addon_updater_ignore) 970 | bpy.utils.register_class(addon_updater_end_background) 971 | 972 | # special situation: we just updated the addon, show a popup 973 | # to tell the user it worked 974 | # should be enclosed in try/catch in case other issues arise 975 | showReloadPopup() 976 | 977 | 978 | def unregister(): 979 | bpy.utils.unregister_class(addon_updater_install_popup) 980 | bpy.utils.unregister_class(addon_updater_check_now) 981 | bpy.utils.unregister_class(addon_updater_update_now) 982 | bpy.utils.unregister_class(addon_updater_update_target) 983 | bpy.utils.unregister_class(addon_updater_install_manually) 984 | bpy.utils.unregister_class(addon_updater_updated_successful) 985 | bpy.utils.unregister_class(addon_updater_restore_backup) 986 | bpy.utils.unregister_class(addon_updater_ignore) 987 | bpy.utils.unregister_class(addon_updater_end_background) 988 | 989 | # clear global vars since they may persist if not restarting blender 990 | global ran_autocheck_install_popup 991 | ran_autocheck_install_popup = False 992 | 993 | global ran_update_sucess_popup 994 | ran_update_sucess_popup = False 995 | 996 | global ran_background_check 997 | ran_background_check = False -------------------------------------------------------------------------------- /io_scene_wmo/developer_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import pkgutil 4 | import importlib 5 | 6 | 7 | def setup_addon_modules(path, package_name, reload): 8 | """ 9 | Imports and reloads all modules in this addon. 10 | 11 | path -- __path__ from __init__.py 12 | package_name -- __name__ from __init__.py 13 | 14 | Individual modules can define a __reload_order_index__ property which 15 | will be used to reload the modules in a specific order. The default is 0. 16 | """ 17 | def get_submodule_names(path = path[0], root = ""): 18 | module_names = [] 19 | for importer, module_name, is_package in pkgutil.iter_modules([path]): 20 | if is_package: 21 | sub_path = os.path.join(path, module_name) 22 | sub_root = root + module_name + "." 23 | module_names.extend(get_submodule_names(sub_path, sub_root)) 24 | else: 25 | module_names.append(root + module_name) 26 | return module_names 27 | 28 | def import_submodules(names): 29 | modules = [] 30 | for name in names: 31 | modules.append(importlib.import_module("." + name, package_name)) 32 | return modules 33 | 34 | def reload_modules(modules): 35 | modules.sort(key = lambda module: getattr(module, "__reload_order_index__", 0)) 36 | for module in modules: 37 | importlib.reload(module) 38 | 39 | names = get_submodule_names() 40 | modules = import_submodules(names) 41 | if reload: 42 | reload_modules(modules) 43 | return modules -------------------------------------------------------------------------------- /io_scene_wmo/idproperty/idproperty.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module adds the concept of an IDProperty (like an IntProperty, or 3 | StringProperty). The IDProperty allows us to link to another object by name, 4 | will stay linked even if that object's name changes, and will automatically 5 | unlink if that object goes away. 6 | 7 | Technically, this is accomplished by giving every object a unique id, accessed 8 | by the .id attribute. In order to put a unique id on every object, we decide to 9 | lazily generate the ids -- only at the time of accessing the id attribute will 10 | the id be created, if it doesn't already exist. This allows the appearance of 11 | every object to have an id automatically. 12 | 13 | Also, if data is linked from one scene to another, the linked object in the new 14 | scene may have an id that is taken by another object in the scene. In this 15 | case, any reference to the id may be incorrect, since we have no way of knowing 16 | which object is the authentic one. 17 | 18 | Random note to Blender devs: I love Blender and have been using it for over 10 19 | years! Thanks for all your hard work! If there is any interest in bringing 20 | this functionality to core, I would love to chat about it. I think it could be 21 | achieved relatively simply, just by introducing unique ids to native objects, 22 | enforcing their uniqueness even in the case of duplication/linking, and 23 | introducing a fast lookup from id -> object. 24 | """ 25 | 26 | 27 | import bpy 28 | import blf 29 | import bgl 30 | from bpy.app import handlers 31 | from bpy.utils import register_module, unregister_module 32 | from bpy import props as p 33 | from contextlib import contextmanager 34 | import json 35 | from . import ray_casting 36 | from .ray_casting import rayCasting 37 | 38 | 39 | # some arbitrarily large number representing the range of a set of ids within a 40 | # library. we use this in case a model has been linked to the current scene 41 | # from a library, in which case, ids may be conflicting. we'll use this number 42 | # to help determine an offset to the linked object's id 43 | LIB_ID_SPACE = 10000000 44 | 45 | ID_TO_HASH = {} 46 | HASH_TO_NAME = {} 47 | 48 | SUPPORTED_COLLECTIONS = ( 49 | ("objects", "Object"), 50 | ) 51 | 52 | 53 | class IDPropertyOpMixin(object): 54 | bl_label = "" 55 | to_populate_data = p.StringProperty() 56 | to_populate_field = p.StringProperty() 57 | 58 | 59 | @property 60 | def ob(self): 61 | data = eval(self.to_populate_data) 62 | ob_name = getattr(data, self.to_populate_field) 63 | return bpy.context.scene.objects.get(ob_name) 64 | 65 | @ob.setter 66 | def ob(self, new_ob): 67 | ob_name = new_ob.name if new_ob else "" 68 | data = eval(self.to_populate_data) 69 | setattr(data, self.to_populate_field, ob_name) 70 | 71 | @classmethod 72 | def poll(self, ctx): 73 | return has_active_3d_view() 74 | 75 | 76 | class ObjectPickerOperator(IDPropertyOpMixin, bpy.types.Operator): 77 | bl_idname = "view3d.object_picker_operator" 78 | bl_label = "Object Picker Operator" 79 | 80 | def execute(self, ctx): 81 | 82 | rayCasting.to_populate_data = self.to_populate_data 83 | rayCasting.to_populate_field = self.to_populate_field 84 | 85 | with in_3dview(ctx) as override: 86 | test = bpy.ops.view3d.modal_operator_raycast(override, 'INVOKE_DEFAULT') 87 | 88 | return {'FINISHED'} 89 | 90 | 91 | class ViewOperatorRayCast(bpy.types.Operator): 92 | """Modal object selection with a ray cast""" 93 | bl_idname = "view3d.modal_operator_raycast" 94 | bl_label = "RayCast View Operator" 95 | 96 | def modal(self, context, event): 97 | bpy.context.window.cursor_set("EYEDROPPER") 98 | if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'MOUSEMOVE'}: 99 | ray_casting.main(context, event) 100 | 101 | return {'PASS_THROUGH'} 102 | elif event.type == 'LEFTMOUSE': 103 | bpy.context.window.cursor_set("DEFAULT") 104 | ray_casting.main(context, event) 105 | 106 | if hasattr(rayCasting, 'to_populate_data') and hasattr(rayCasting, 'to_populate_field') and hasattr(rayCasting, 'result'): 107 | setattr(eval(rayCasting.to_populate_data), rayCasting.to_populate_field, rayCasting.result.name) 108 | 109 | return {'FINISHED'} 110 | elif event.type in {'RIGHTMOUSE', 'ESC'}: 111 | bpy.context.window.cursor_set("DEFAULT") 112 | rayCasting.result = None 113 | return {'CANCELLED'} 114 | 115 | return {'RUNNING_MODAL'} 116 | 117 | def invoke(self, context, event): 118 | 119 | if context.space_data.type == 'VIEW_3D' and context.active_object.mode != 'EDIT': 120 | context.window_manager.modal_handler_add(self) 121 | return {'RUNNING_MODAL'} 122 | else: 123 | rayCasting.result = False 124 | self.report({'WARNING'}, "Active space is not a View3D or active mode is EDIT") 125 | return {'CANCELLED'} 126 | 127 | 128 | class FindSelected(IDPropertyOpMixin, bpy.types.Operator): 129 | bl_idname = "idproperty.find_selected" 130 | 131 | def execute(self, ctx): 132 | if self.ob: 133 | for ob in ctx.scene.objects: 134 | ob.select = False 135 | 136 | ctx.scene.objects.active = self.ob 137 | self.ob.select = True 138 | 139 | with in_3dview(ctx) as override: 140 | bpy.ops.view3d.view_selected(override) 141 | 142 | return {"FINISHED"} 143 | 144 | 145 | def has_active_3d_view(): 146 | return len(list(all_3d_views())) > 0 147 | 148 | def all_3d_views(): 149 | for area in bpy.context.screen.areas: 150 | if area.type == "VIEW_3D": 151 | for region in area.regions: 152 | if region.type == "WINDOW": 153 | yield (area, region) 154 | 155 | 156 | @contextmanager 157 | def in_3dview(ctx): 158 | try: 159 | area, region = list(all_3d_views())[0] 160 | except IndexError: 161 | raise Exception("no 3d region found") 162 | 163 | override = ctx.copy() 164 | override.update({"area": area, "region": region}) 165 | yield override 166 | 167 | 168 | 169 | def layout_id_prop(layout, data, prop): 170 | prop_obj = data.bl_rna.properties[prop] 171 | prop_name = prop_obj.name 172 | value_key = _create_value_key(prop_name) 173 | ref_id = data.get(value_key, None) 174 | 175 | field_name = json.loads(prop_obj.description)["field_name"] 176 | 177 | row = layout.row(align=True) 178 | row.prop_search(data, prop, bpy.context.scene, field_name) 179 | 180 | if field_name == "objects": 181 | op_props = row.operator("view3d.object_picker_operator", emboss=True, text="", icon="EYEDROPPER") 182 | op_props.to_populate_data = repr(data) 183 | op_props.to_populate_field = prop 184 | 185 | op_props = row.operator(FindSelected.bl_idname, emboss=True, icon="VIEWZOOM") 186 | op_props.to_populate_data = repr(data) 187 | op_props.to_populate_field = prop 188 | 189 | 190 | def _get_global_id(field): 191 | """ internal helper for getting the true unique counter id by looking 192 | at all scenes and picking the highest value """ 193 | field += "_id_counter" 194 | scenes = list(bpy.data.scenes) 195 | scenes.sort(key=lambda s: getattr(s, field), reverse=True) 196 | max_id = getattr(scenes[0], field) 197 | return max_id 198 | 199 | def _inc_global_id(field, old_max_id): 200 | """ internal helper for incrementing the unique object counter id by making 201 | sure that all scenes have the same value """ 202 | field += "_id_counter" 203 | new_id = old_max_id + 1 204 | for scene in bpy.data.scenes: 205 | setattr(scene, field, new_id) 206 | return new_id 207 | 208 | 209 | 210 | def get_by_id(data_field, id): 211 | data = getattr(bpy.data, data_field) 212 | 213 | id_to_hash = ID_TO_HASH[data_field] 214 | hash_to_name = HASH_TO_NAME[data_field] 215 | 216 | hash = id_to_hash.get(id, None) 217 | ob_name = hash_to_name.get(hash) 218 | 219 | ob = None 220 | if ob_name: 221 | ob = data.get(ob_name, None) 222 | 223 | return ob 224 | 225 | 226 | 227 | def _create_id_getter(field): 228 | def fn(self): 229 | id = self.get("id", 0) 230 | if not id: 231 | id = _get_global_id(field) 232 | self["id"] = id 233 | _inc_global_id(field, id) 234 | 235 | # if our object lives in another blend file, and has been linked into this 236 | # file, we're going to offset all of its ids by some amount 237 | lib_offset = 0 238 | if self.library: 239 | lib_offset = (self.library.id+1) * LIB_ID_SPACE 240 | 241 | return id + lib_offset 242 | return fn 243 | 244 | 245 | def _create_value_key(name): 246 | return name + "_id" 247 | 248 | 249 | def create_getter(data_field, value_key): 250 | 251 | def fn(self): 252 | data = getattr(bpy.context.scene, data_field) 253 | 254 | ob_id = self.get(value_key, None) 255 | 256 | id_to_hash = ID_TO_HASH[data_field] 257 | hash_to_name = HASH_TO_NAME[data_field] 258 | 259 | ob_hash = id_to_hash.get(ob_id, None) 260 | ob_name = hash_to_name.get(ob_hash, None) 261 | exists = ob_name is not None and ob_name in data 262 | 263 | if not exists: 264 | for name, ob in data.items(): 265 | if ob_hash == hash(ob): 266 | hash_to_name[ob_hash] = name 267 | ob_name = name 268 | break 269 | 270 | if ob_name is None: 271 | ob_name = "" 272 | return ob_name 273 | return fn 274 | 275 | 276 | 277 | def create_setter(data_field, value_key, validator=None): 278 | 279 | def fn(self, value): 280 | data = getattr(bpy.context.scene, data_field) 281 | 282 | if value == "": 283 | self[value_key] = 0 284 | 285 | else: 286 | ob = data.get(value, None) 287 | if ob: 288 | valid = True 289 | if validator: 290 | valid = validator(ob) 291 | 292 | if valid: 293 | ob_hash = hash(ob) 294 | expected_hash = ID_TO_HASH[data_field].get(ob.id, None) 295 | 296 | # the object is new, and doesn't have an entry in the hash 297 | # lookup. it is entirely possible that this is a duplicated 298 | # object and it shares its id with other objects. so let's 299 | # re-evaluate its id 300 | if ob_hash != expected_hash: 301 | ob["id"] = 0 302 | ID_TO_HASH[data_field][ob.id] = ob_hash 303 | HASH_TO_NAME[data_field][ob_hash] = ob.name 304 | 305 | self[value_key] = ob.id 306 | 307 | return fn 308 | 309 | 310 | def _create_id_property(field_name): 311 | def fn(*args, **kwargs): 312 | """ the main class. """ 313 | value_key = _create_value_key(kwargs["name"]) 314 | validator = kwargs.pop("validator", None) 315 | 316 | kwargs["get"] = create_getter(field_name, value_key) 317 | kwargs["set"] = create_setter(field_name, value_key, validator) 318 | 319 | payload = { 320 | "field_name": field_name, 321 | } 322 | kwargs["description"] = json.dumps(payload) 323 | 324 | prop = p.StringProperty(*args, **kwargs) 325 | return prop 326 | 327 | return fn 328 | 329 | 330 | for col_name, type_name in SUPPORTED_COLLECTIONS: 331 | prop_name = type_name + "IDProperty" 332 | globals()[prop_name] = _create_id_property(col_name) 333 | 334 | 335 | 336 | @handlers.persistent 337 | def load_file(_=None): 338 | for col_name, _ in SUPPORTED_COLLECTIONS: 339 | id_to_hash = {} 340 | hash_to_name = {} 341 | 342 | ID_TO_HASH[col_name] = id_to_hash 343 | HASH_TO_NAME[col_name] = hash_to_name 344 | 345 | col = getattr(bpy.context.scene, col_name) 346 | all_obs = sorted(list(col), key=lambda ob: ob.name, reverse=True) 347 | 348 | for ob in all_obs: 349 | # on load, if we encounter an object with a dup id. unset it and let it 350 | # regenerate as a unique id 351 | if ob.id in id_to_hash: 352 | ob["id"] = 0 353 | 354 | id_to_hash[ob.id] = hash(ob) 355 | hash_to_name[hash(ob)] = ob.name 356 | 357 | def load_file_shim(_=None): 358 | """ an ugly shim for calling load_file() "immiediately", which accesses 359 | bpy.data (typically not allowed in an addon's register()) """ 360 | handlers.scene_update_pre.remove(load_file_shim) 361 | load_file() 362 | 363 | 364 | def register(): 365 | 366 | for col_name, type_name in SUPPORTED_COLLECTIONS: 367 | type = getattr(bpy.types, type_name) 368 | type.id = p.IntProperty(name="unique id", get=_create_id_getter(col_name)) 369 | 370 | counter_name = col_name + "_id_counter" 371 | setattr(bpy.types.Scene, counter_name, 372 | p.IntProperty(name="unique id counter", default=1)) 373 | 374 | handlers.load_post.append(load_file) 375 | handlers.scene_update_pre.append(load_file_shim) 376 | 377 | 378 | def unregister(): 379 | 380 | for col_name, type_name in SUPPORTED_COLLECTIONS: 381 | type = getattr(bpy.types, type_name) 382 | del type.id 383 | counter_name = col_name + "_id_counter" 384 | delattr(bpy.types.Scene, counter_name) 385 | 386 | handlers.load_post.remove(load_file) 387 | -------------------------------------------------------------------------------- /io_scene_wmo/idproperty/ray_casting.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from bpy_extras import view3d_utils 3 | 4 | class rayCasting(): 5 | def __init__(self): 6 | self.result = None 7 | self.to_populate_data = None 8 | self.to_populate_field = None 9 | 10 | def main(context, event): 11 | """Run this function on left mouse, execute the ray cast""" 12 | # get the context arguments 13 | scene = context.scene 14 | region = context.region 15 | rv3d = context.region_data 16 | coord = event.mouse_region_x, event.mouse_region_y 17 | 18 | # get the ray from the viewport and mouse 19 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord) 20 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord) 21 | 22 | ray_target = ray_origin + view_vector 23 | 24 | def visible_objects_and_duplis(): 25 | """Loop over (object, matrix) pairs (mesh only)""" 26 | 27 | for obj in context.visible_objects: 28 | if obj.type == 'MESH': 29 | yield (obj, obj.matrix_world.copy()) 30 | 31 | if obj.dupli_type != 'NONE': 32 | obj.dupli_list_create(scene) 33 | for dob in obj.dupli_list: 34 | obj_dupli = dob.object 35 | if obj_dupli.type == 'MESH': 36 | yield (obj_dupli, dob.matrix.copy()) 37 | 38 | obj.dupli_list_clear() 39 | 40 | def obj_ray_cast(obj, matrix): 41 | """Wrapper for ray casting that moves the ray into object space""" 42 | 43 | # get the ray relative to the object 44 | matrix_inv = matrix.inverted() 45 | ray_origin_obj = matrix_inv * ray_origin 46 | ray_target_obj = matrix_inv * ray_target 47 | ray_direction_obj = ray_target_obj - ray_origin_obj 48 | 49 | # cast the ray 50 | success, location, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj) 51 | 52 | if success: 53 | return location, normal, face_index 54 | else: 55 | return None, None, None 56 | 57 | # cast rays and find the closest object 58 | best_length_squared = -1.0 59 | best_obj = None 60 | 61 | for obj, matrix in visible_objects_and_duplis(): 62 | if obj.type == 'MESH': 63 | hit, normal, face_index = obj_ray_cast(obj, matrix) 64 | if hit is not None: 65 | hit_world = matrix * hit 66 | scene.cursor_location = hit_world 67 | length_squared = (hit_world - ray_origin).length_squared 68 | if best_obj is None or length_squared < best_length_squared: 69 | best_length_squared = length_squared 70 | best_obj = obj 71 | 72 | # now we have the object under the mouse cursor, 73 | # we could do lots of stuff but for the example just select. 74 | if best_obj is not None: 75 | rayCasting.result = best_obj 76 | -------------------------------------------------------------------------------- /io_scene_wmo/m2/import_m2.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | from . import m2 as m2_ 4 | from . import skin as skin_ 5 | 6 | 7 | def m2_to_blender_mesh(dir, filepath, filedata): 8 | """Import World of Warcraft M2 model to scene.""" 9 | 10 | print("\nImporting model: <<" + filepath + ">>") 11 | 12 | active_obj = bpy.context.scene.objects.active 13 | is_select = bpy.context.scene.objects.active.select if active_obj else False 14 | 15 | m2_path = os.path.splitext(filepath)[0] + ".m2" 16 | skin_path = os.path.splitext(filepath)[0] + "00.skin" 17 | 18 | m2_file = filedata.read_file(m2_path) 19 | skin_file = filedata.read_file(skin_path) 20 | 21 | m2 = m2_.M2File((m2_file, os.path.basename(m2_path))) 22 | skin = skin_.SkinFile((skin_file, os.path.basename(skin_path))) 23 | 24 | if not m2 or not skin: 25 | print("Failed to import: <<" + filepath + ">> Model import seems to have failed.") 26 | 27 | name = m2.name.decode("utf-8") 28 | 29 | vertices = [] 30 | polygons = [] 31 | normals = [] 32 | tex_coords = [] 33 | 34 | for vertex in m2.vertices: 35 | vertices.append((vertex.pos.x, vertex.pos.y, vertex.pos.z)) 36 | tex_coords.append(vertex.uv) 37 | normals.append(vertex.normal) 38 | 39 | for polygon in skin.tri: 40 | face = [] 41 | for index in polygon.indices: 42 | face.append(skin.indices[index].Id) 43 | 44 | polygons.append(face) 45 | 46 | # create mesh 47 | mesh = bpy.data.meshes.new(name) 48 | mesh.from_pydata(vertices, [], polygons) 49 | 50 | for poly in mesh.polygons: 51 | poly.use_smooth = True 52 | 53 | # set normals 54 | for index, vertex in enumerate(mesh.vertices): 55 | vertex.normal = normals[index] 56 | 57 | # set uv 58 | uv1 = mesh.uv_textures.new("UVMap") 59 | uv_layer1 = mesh.uv_layers[0] 60 | for i in range(len(uv_layer1.data)): 61 | uv = tex_coords[mesh.loops[i].vertex_index] 62 | uv_layer1.data[i].uv = (uv[0], 1 - uv[1]) 63 | 64 | # unpack and convert textures 65 | texture_paths = [] 66 | for texture in m2.textures: 67 | texture_paths.append(texture.name.decode("utf-8").rstrip('\0')) 68 | 69 | filedata.extract_textures_as_png(dir, texture_paths) 70 | 71 | # set textures 72 | for batch in skin.texunit: 73 | m2_mesh = skin.mesh[batch.submesh] 74 | 75 | # check if forced decompression is required here !!! 76 | path = os.path.splitext( 77 | m2.textures[m2.tex_lookup[batch.texture].Id].name.decode("utf-8").rstrip('\0') 78 | )[0] + ".png" 79 | 80 | img = None 81 | 82 | try: 83 | img = bpy.data.images.load(os.path.join(dir, path), check_existing=True) 84 | except: 85 | print("\nFailed to load texture: " + path + " File is missing or invalid.") 86 | 87 | if img: 88 | for i in range(m2_mesh.tri_offset // 3, (m2_mesh.tri_offset + m2_mesh.num_tris) // 3): 89 | uv1.data[i].image = img 90 | 91 | # create object 92 | scn = bpy.context.scene 93 | 94 | for o in scn.objects: 95 | o.select = False 96 | 97 | nobj = bpy.data.objects.new(name, mesh) 98 | scn.objects.link(nobj) 99 | 100 | if active_obj: 101 | bpy.context.scene.objects.active = active_obj 102 | active_obj.select = is_select 103 | 104 | return nobj 105 | 106 | 107 | def wmv_get_last_m2(): 108 | """Get the path of last M2 model from WoWModelViewer or similar log.""" 109 | 110 | preferences = bpy.context.user_preferences.addons.get("io_scene_wmo").preferences 111 | 112 | if preferences.wmv_path: 113 | 114 | lines = open(preferences.wmv_path).readlines() 115 | 116 | for line in reversed(lines): 117 | if 'Loading model:' in line: 118 | return line[25:].split(",", 1)[0].rstrip("\n") 119 | 120 | 121 | class WoW_WMO_Import_Doodad_WMV(bpy.types.Operator): 122 | bl_idname = 'scene.wow_wmo_import_doodad_from_wmv' 123 | bl_label = 'Import last M2 from WMV' 124 | bl_description = 'Import last M2 from WoW Model Viewer' 125 | bl_options = {'REGISTER'} 126 | 127 | def execute(self, context): 128 | 129 | game_data = getattr(bpy, "wow_game_data", None) 130 | 131 | if not game_data or not game_data.files: 132 | self.report({'ERROR'}, "Failed to import model. Connect to game client first.") 133 | return {'CANCELLED'} 134 | 135 | dir = bpy.path.abspath("//") if bpy.data.is_saved else None 136 | m2_path = wmv_get_last_m2() 137 | 138 | if not m2_path: 139 | self.report({'ERROR'}, """WoW Model Viewer log contains no model entries. 140 | Make sure to use compatible WMV version or open an .m2 there.""") 141 | return {'CANCELLED'} 142 | 143 | obj = None 144 | 145 | if dir: 146 | try: 147 | obj = m2_to_blender_mesh(dir, m2_path, game_data) 148 | except NotImplementedError: 149 | bpy.ops.mesh.primitive_cube_add() 150 | obj = bpy.context.scene.objects.active 151 | self.report({'WARNING'}, "Model is encrypted. Placeholder is imported instead.") 152 | except: 153 | bpy.ops.mesh.primitive_cube_add() 154 | obj = bpy.context.scene.objects.active 155 | self.report({'WARNING'}, "Failed to import model. Placeholder is imported instead.") 156 | else: 157 | self.report({'INFO'}, "Imported model: {}".format(m2_path)) 158 | 159 | if bpy.context.scene.objects.active and bpy.context.scene.objects.active.select: 160 | obj.location = bpy.context.scene.objects.active.location 161 | else: 162 | obj.location = bpy.context.scene.cursor_location 163 | 164 | obj.WoWDoodad.Enabled = True 165 | obj.WoWDoodad.Path = m2_path 166 | 167 | bpy.ops.object.select_all(action='DESELECT') 168 | bpy.context.scene.objects.active = obj 169 | obj.select = True 170 | 171 | else: 172 | self.report({'ERROR'}, "Failed to import model. " 173 | "Save your blendfile first.") 174 | return {'CANCELLED'} 175 | 176 | return {'FINISHED'} 177 | -------------------------------------------------------------------------------- /io_scene_wmo/m2/skin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import struct 3 | import array 4 | import io 5 | from .wowfile import * 6 | from . import wowfile 7 | 8 | class SkinHeader: 9 | def __init__(self): 10 | self.magic = 1313426259 11 | self.Indices = Chunk() 12 | self.Triangles = Chunk() 13 | self.Properties = Chunk() 14 | self.Submeshes = Chunk() 15 | self.TextureUnits = Chunk() 16 | self.lod = 0 17 | def unpack(self,f): 18 | self.magic, = struct.unpack("i",f.read(4)) 19 | self.Indices.unpack(f) 20 | self.Triangles.unpack(f) 21 | self.Properties.unpack(f) 22 | self.Submeshes.unpack(f) 23 | self.TextureUnits.unpack(f) 24 | self.lod, = struct.unpack("i",f.read(4)) 25 | return self 26 | def pack(self): 27 | ret = struct.pack("i",self.magic) 28 | ret += self.Indices.pack() 29 | ret += self.Triangles.pack() 30 | ret += self.Properties.pack() 31 | ret += self.Submeshes.pack() 32 | ret += self.TextureUnits.pack() 33 | ret += struct.pack("i", self.lod) 34 | return ret 35 | 36 | class Mesh: 37 | def __init__(self): 38 | self.mesh_id = 0 39 | self.vert_offset = 0 40 | self.num_verts = 0 41 | self.tri_offset = 0 42 | self.num_tris = 0 43 | self.num_bones = 0 44 | self.start_bone = 0 45 | self.unknown = 0 46 | self.rootbone = 0 47 | self.bound = Bounds() 48 | 49 | def unpack(self,f): 50 | self.mesh_id, = struct.unpack("i",f.read(4)) 51 | self.vert_offset, = struct.unpack("H",f.read(2)) 52 | self.num_verts, = struct.unpack("H",f.read(2)) 53 | self.tri_offset, = struct.unpack("H",f.read(2)) 54 | self.num_tris, = struct.unpack("H",f.read(2)) 55 | self.num_bones, = struct.unpack("H",f.read(2)) 56 | self.start_bone, = struct.unpack("H",f.read(2)) 57 | self.unknown, = struct.unpack("H",f.read(2)) 58 | self.rootbone, = struct.unpack("H",f.read(2)) 59 | self.bound.unpack(f) 60 | return self 61 | def pack(self): 62 | ret = struct.pack("i",self.mesh_id) 63 | ret += struct.pack("H",self.vert_offset) 64 | ret += struct.pack("H", self.num_verts) 65 | ret += struct.pack("H", self.tri_offset) 66 | ret += struct.pack("H", self.num_tris) 67 | ret += struct.pack("H", self.num_bones) 68 | ret += struct.pack("H", self.start_bone) 69 | ret += struct.pack("H", self.unknown) 70 | ret += struct.pack("H", self.rootbone) 71 | ret += self.bound.pack() 72 | return ret 73 | 74 | 75 | class Material: 76 | def __init__(self): 77 | self.flags = 0 78 | self.shading = 0 79 | self.submesh = 0 80 | self.submesh2 = 0 81 | self.color = -1 82 | self.renderflag = 0 83 | self.texunit = 0 84 | self.mode = 0 85 | self.texture = 0 86 | self.texunit2 = 0 87 | self.transparency = 0 88 | self.animation = 0 89 | def unpack(self,f): 90 | self.flags, = struct.unpack("H",f.read(2)) 91 | self.shading, = struct.unpack("H",f.read(2)) 92 | self.submesh, = struct.unpack("H",f.read(2)) 93 | self.submesh2, = struct.unpack("H",f.read(2)) 94 | self.color, = struct.unpack("h",f.read(2)) 95 | self.renderflag, = struct.unpack("H",f.read(2)) 96 | self.texunit, = struct.unpack("H",f.read(2)) 97 | self.mode, = struct.unpack("H",f.read(2)) 98 | self.texture, = struct.unpack("H",f.read(2)) 99 | self.texunit2, = struct.unpack("H",f.read(2)) 100 | self.transparency, = struct.unpack("H",f.read(2)) 101 | self.animation, = struct.unpack("H",f.read(2)) 102 | return self 103 | def pack(self): 104 | ret = struct.pack("H",self.flags) 105 | ret += struct.pack("H",self.shading) 106 | ret += struct.pack("H",self.submesh) 107 | ret += struct.pack("H",self.submesh2) 108 | ret += struct.pack("h",self.color) 109 | ret += struct.pack("H",self.renderflag) 110 | ret += struct.pack("H",self.texunit) 111 | ret += struct.pack("H",self.mode) 112 | ret += struct.pack("H",self.texture) 113 | ret += struct.pack("H",self.texunit2) 114 | ret += struct.pack("H",self.transparency) 115 | ret += struct.pack("H",self.animation) 116 | return ret 117 | 118 | class Propertie: 119 | def __init__(self): 120 | self.Bones = (0,0,0,0) 121 | def unpack(self,f): 122 | self.Bones = struct.unpack("4B",f.read(4)) 123 | return self 124 | def pack(self): 125 | return struct.pack("4B",self.Bones[0],self.Bones[1],self.Bones[2],self.Bones[3]) 126 | 127 | class SkinFile: 128 | def __init__(self, file): 129 | f = open(file,"r+b") if type(file) == type("") else io.BytesIO(file[0]) 130 | 131 | self.header = SkinHeader() 132 | self.header.unpack(f) 133 | self.indices = ReadBlock(f,self.header.Indices,Lookup) 134 | self.header.Triangles.count //= 3; 135 | self.tri = ReadBlock(f,self.header.Triangles,Triangle) 136 | self.prop = ReadBlock(f,self.header.Properties,Propertie) 137 | self.mesh = ReadBlock(f,self.header.Submeshes,Mesh) 138 | self.texunit = ReadBlock(f,self.header.TextureUnits,Material) 139 | 140 | 141 | f.close() 142 | 143 | def write(self,filename): 144 | f = open(filename,"wb") 145 | 146 | f.write(self.header.pack()) 147 | 148 | WriteBlock(f,self.header.Indices,self.indices) 149 | WriteBlock(f,self.header.Triangles,self.tri) 150 | self.header.Triangles.count *= 3; 151 | WriteBlock(f,self.header.Properties,self.prop) 152 | WriteBlock(f,self.header.Submeshes,self.mesh) 153 | WriteBlock(f,self.header.TextureUnits,self.texunit) 154 | 155 | f.seek(0,SEEK_SET) 156 | f.write(self.header.pack()) 157 | 158 | f.close() 159 | 160 | 161 | -------------------------------------------------------------------------------- /io_scene_wmo/m2/wowfile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #This file contains some helpers for the files 3 | import struct 4 | from sys import version_info 5 | if version_info < (3,0): 6 | xrange = xrange 7 | else: 8 | xrange = range 9 | 10 | SEEK_SET = 0 11 | SEEK_CUR = 1 12 | SEEK_END = 2 13 | 14 | def FillLine(f): 15 | i = f.tell() 16 | n = (16 - ((i) % 16))#Calculate the bytes needed to fill up the 0x10 ( == 16) 17 | for i in xrange(n): 18 | f.write("\0")#write 0-Byte 19 | 20 | return f 21 | 22 | def ReadBlock(f,chunk,func,animfiles = None): 23 | f.seek(chunk.offset) 24 | ret = [] 25 | if(animfiles is None): 26 | for i in xrange(chunk.count): 27 | temp = func().unpack(f) 28 | ret.append(temp) 29 | else: 30 | for i in xrange(chunk.count): 31 | temp = func().unpack(f,animfiles) 32 | ret.append(temp) 33 | return ret 34 | 35 | def WriteBlock(f,chunk,block): 36 | if(chunk.count != 0): 37 | chunk.offset = f.tell() 38 | for i in xrange(chunk.count): 39 | temp = block[i].pack() 40 | f.write(temp) 41 | FillLine(f) 42 | else: 43 | chunk.offset = 0 44 | 45 | 46 | class Lookup: 47 | def __init__(self): 48 | self.Id = 0 49 | def __str__(self): 50 | return "("+str(self.Id)+")" 51 | def unpack(self,f): 52 | self.Id, = struct.unpack("h",f.read(2)) 53 | return self 54 | def pack(self): 55 | return struct.pack("h",self.Id) 56 | 57 | 58 | class Chunk: 59 | def __init__(self): 60 | self.count = 0 61 | self.offset = 0 62 | def unpack(self,f): 63 | self.count, = struct.unpack("i",f.read(4)) 64 | self.offset, = struct.unpack("i",f.read(4)) 65 | return self 66 | def pack(self): 67 | ret = struct.pack("2i",self.count,self.offset) 68 | return ret 69 | 70 | class Triangle: 71 | def __init__(self): 72 | self.indices = (0,0,0) 73 | def unpack(self,f): 74 | self.indices = struct.unpack("3H",f.read(6)) 75 | return self 76 | def pack(self): 77 | return struct.pack("3H",self.indices[0],self.indices[1],self.indices[2]) 78 | 79 | class Vec3: 80 | def __init__(self,x = 0.0,y = 0.0, z = 0.0): 81 | self.x = float(x) 82 | self.y = float(y) 83 | self.z = float(z) 84 | def __str__(self): 85 | return "{ "+str(self.x)+" , "+str(self.y)+ " , "+str(self.z)+" }" 86 | 87 | def __add__(self, val): 88 | return Vec3( self.x + val.x, self.y + val.y , self.z + val.z) 89 | 90 | def __sub__(self,val): 91 | return Vec3( self.x - val.x, self.y - val.y , self.z - val.z) 92 | 93 | def __iadd__(self, val): 94 | self.x = val.x + self.x 95 | self.y = val.y + self.y 96 | self.z = val.z + self.z 97 | return self 98 | 99 | def __isub__(self, val): 100 | self.x = self.x - val.x 101 | self.y = self.y - val.y 102 | self.z = self.z - val.z 103 | return self 104 | 105 | def unpack(self,f): 106 | self.x, = struct.unpack("f",f.read(4)) 107 | self.y, = struct.unpack("f",f.read(4)) 108 | self.z, = struct.unpack("f",f.read(4)) 109 | return self 110 | 111 | def pack(self): 112 | ret = struct.pack("f",self.x) 113 | ret += struct.pack("f",self.y) 114 | ret += struct.pack("f",self.z) 115 | return ret 116 | 117 | class Vec2: 118 | def __init__(self): 119 | self.x = 0 120 | self.y = 0 121 | def __str__(self): 122 | return "{ "+str(self.x)+" , "+str(self.y)+" }" 123 | 124 | def unpack(self,f): 125 | self.x, = struct.unpack("f",f.read(4)) 126 | self.y, = struct.unpack("f",f.read(4)) 127 | return self 128 | def pack(self): 129 | ret = struct.pack("f",self.x) 130 | ret += struct.pack("f",self.y) 131 | return ret 132 | 133 | class Vec9: 134 | def __init__(self): 135 | self.x1 = 0 136 | self.x2 = 0 137 | self.x3 = 0 138 | self.y1 = 0 139 | self.y2 = 0 140 | self.y3 = 0 141 | self.z1 = 0 142 | self.z2 = 0 143 | self.z3 = 0 144 | def __str__(self): 145 | return "{ "+str(self.x1)+" , "+str(self.x2)+" , "+str(self.x3)+" , "+str(self.y1)+ " , "+str(self.y2)+ " , "+str(self.y3)+ " , "+str(self.z1)+ " , "+str(self.z2)+ " , "+str(self.z3)+" }" 146 | def unpack(self,f): 147 | self.x1, = struct.unpack("f",f.read(4)) 148 | self.x2, = struct.unpack("f",f.read(4)) 149 | self.x3, = struct.unpack("f",f.read(4)) 150 | self.y1, = struct.unpack("f",f.read(4)) 151 | self.y2, = struct.unpack("f",f.read(4)) 152 | self.y3, = struct.unpack("f",f.read(4)) 153 | self.z1, = struct.unpack("f",f.read(4)) 154 | self.z2, = struct.unpack("f",f.read(4)) 155 | self.z3, = struct.unpack("f",f.read(4)) 156 | return self 157 | def pack(self): 158 | ret = struct.pack("f",self.x1) 159 | ret += struct.pack("f",self.x2) 160 | ret += struct.pack("f",self.x3) 161 | ret += struct.pack("f",self.y1) 162 | ret += struct.pack("f",self.y2) 163 | ret += struct.pack("f",self.y3) 164 | ret += struct.pack("f",self.z1) 165 | ret += struct.pack("f",self.z2) 166 | ret += struct.pack("f",self.z3) 167 | return ret 168 | 169 | class Quat: 170 | def __init__(self): 171 | self.x = 0 172 | self.y = 0 173 | self.z = 0 174 | self.w = 0 175 | def __str__(self): 176 | return "{ "+str(self.x)+" , "+str(self.y)+" , "+str(self.z)+" , "+str(self.w)+" }" 177 | def unpack(self,f): 178 | self.x, = struct.unpack("h",f.read(2)) 179 | self.y, = struct.unpack("h",f.read(2)) 180 | self.z, = struct.unpack("h",f.read(2)) 181 | self.w, = struct.unpack("h",f.read(2)) 182 | return self 183 | def pack(self): 184 | ret = struct.pack("h",self.x) 185 | ret += struct.pack("h",self.y) 186 | ret += struct.pack("h",self.z) 187 | ret += struct.pack("h",self.w) 188 | return ret 189 | 190 | class Bounds: 191 | def __init__(self): 192 | self.BoundingBox = (0,0,0,0,0,0) 193 | self.Radius = 0 194 | def unpack(self,f): 195 | self.BoundingBox = struct.unpack("6f",f.read(24)) 196 | self.Radius, = struct.unpack("f",f.read(4)) 197 | return self 198 | def pack(self): 199 | ret = struct.pack("6f",self.BoundingBox[0],self.BoundingBox[1],self.BoundingBox[2],self.BoundingBox[3],self.BoundingBox[4],self.BoundingBox[5]) 200 | ret += struct.pack("f",self.Radius) 201 | return ret 202 | -------------------------------------------------------------------------------- /io_scene_wmo/mpq/mpyq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | """ 5 | mpyq is a Python library for reading MPQ (MoPaQ) archives. 6 | """ 7 | 8 | from __future__ import print_function 9 | 10 | import bz2 11 | import os 12 | import struct 13 | import zlib 14 | import re 15 | from collections import namedtuple 16 | from io import BytesIO 17 | 18 | 19 | __author__ = "Aku Kotkavuo" 20 | __version__ = "0.2.5" 21 | 22 | 23 | MPQ_FILE_IMPLODE = 0x00000100 24 | MPQ_FILE_COMPRESS = 0x00000200 25 | MPQ_FILE_ENCRYPTED = 0x00010000 26 | MPQ_FILE_FIX_KEY = 0x00020000 27 | MPQ_FILE_SINGLE_UNIT = 0x01000000 28 | MPQ_FILE_DELETE_MARKER = 0x02000000 29 | MPQ_FILE_SECTOR_CRC = 0x04000000 30 | MPQ_FILE_EXISTS = 0x80000000 31 | 32 | MPQFileHeader = namedtuple('MPQFileHeader', 33 | ''' 34 | magic 35 | header_size 36 | archive_size 37 | format_version 38 | sector_size_shift 39 | hash_table_offset 40 | block_table_offset 41 | hash_table_entries 42 | block_table_entries 43 | ''' 44 | ) 45 | MPQFileHeader.struct_format = '<4s2I2H4I' 46 | 47 | MPQFileHeaderExt = namedtuple('MPQFileHeaderExt', 48 | ''' 49 | extended_block_table_offset 50 | hash_table_offset_high 51 | block_table_offset_high 52 | ''' 53 | ) 54 | MPQFileHeaderExt.struct_format = 'q2h' 55 | 56 | MPQUserDataHeader = namedtuple('MPQUserDataHeader', 57 | ''' 58 | magic 59 | user_data_size 60 | mpq_header_offset 61 | user_data_header_size 62 | ''' 63 | ) 64 | MPQUserDataHeader.struct_format = '<4s3I' 65 | 66 | MPQHashTableEntry = namedtuple('MPQHashTableEntry', 67 | ''' 68 | hash_a 69 | hash_b 70 | locale 71 | platform 72 | block_table_index 73 | ''' 74 | ) 75 | MPQHashTableEntry.struct_format = '2I2HI' 76 | 77 | MPQBlockTableEntry = namedtuple('MPQBlockTableEntry', 78 | ''' 79 | offset 80 | archived_size 81 | size 82 | flags 83 | ''' 84 | ) 85 | MPQBlockTableEntry.struct_format = '4I' 86 | 87 | 88 | class MPQArchive(object): 89 | 90 | def __init__(self, filename, listfile=True): 91 | """Create a MPQArchive object. 92 | 93 | You can skip reading the listfile if you pass listfile=False 94 | to the constructor. The 'files' attribute will be unavailable 95 | if you do this. 96 | """ 97 | if hasattr(filename, 'read'): 98 | self.file = filename 99 | else: 100 | self.file = open(filename, 'rb') 101 | self.header = self.read_header() 102 | self.hash_table = self.read_table('hash') 103 | self.block_table = self.read_table('block') 104 | if listfile: 105 | self.files = self.read_file('(listfile)').splitlines() 106 | else: 107 | self.files = None 108 | 109 | def read_header(self): 110 | """Read the header of a MPQ archive.""" 111 | 112 | def read_mpq_header(offset=None): 113 | if offset: 114 | self.file.seek(offset) 115 | data = self.file.read(32) 116 | header = MPQFileHeader._make( 117 | struct.unpack(MPQFileHeader.struct_format, data)) 118 | header = header._asdict() 119 | if header['format_version'] == 1: 120 | data = self.file.read(12) 121 | extended_header = MPQFileHeaderExt._make( 122 | struct.unpack(MPQFileHeaderExt.struct_format, data)) 123 | header.update(extended_header._asdict()) 124 | return header 125 | 126 | def read_mpq_user_data_header(): 127 | data = self.file.read(16) 128 | header = MPQUserDataHeader._make( 129 | struct.unpack(MPQUserDataHeader.struct_format, data)) 130 | header = header._asdict() 131 | header['content'] = self.file.read(header['user_data_header_size']) 132 | return header 133 | 134 | magic = self.file.read(4) 135 | self.file.seek(0) 136 | 137 | if magic == b'MPQ\x1a': 138 | header = read_mpq_header() 139 | header['offset'] = 0 140 | elif magic == b'MPQ\x1b': 141 | user_data_header = read_mpq_user_data_header() 142 | header = read_mpq_header(user_data_header['mpq_header_offset']) 143 | header['offset'] = user_data_header['mpq_header_offset'] 144 | header['user_data_header'] = user_data_header 145 | else: 146 | raise ValueError("Invalid file header.") 147 | 148 | return header 149 | 150 | def read_table(self, table_type): 151 | """Read either the hash or block table of a MPQ archive.""" 152 | 153 | if table_type == 'hash': 154 | entry_class = MPQHashTableEntry 155 | elif table_type == 'block': 156 | entry_class = MPQBlockTableEntry 157 | else: 158 | raise ValueError("Invalid table type.") 159 | 160 | table_offset = self.header['%s_table_offset' % table_type] 161 | table_entries = self.header['%s_table_entries' % table_type] 162 | key = self._hash('(%s table)' % table_type, 'TABLE') 163 | 164 | self.file.seek(table_offset + self.header['offset']) 165 | data = self.file.read(table_entries * 16) 166 | data = self._decrypt(data, key) 167 | 168 | def unpack_entry(position): 169 | entry_data = data[position*16:position*16+16] 170 | return entry_class._make( 171 | struct.unpack(entry_class.struct_format, entry_data)) 172 | 173 | return [unpack_entry(i) for i in range(table_entries)] 174 | 175 | def get_hash_table_entry(self, filename): 176 | """Get the hash table entry corresponding to a given filename.""" 177 | hash_a = self._hash(filename, 'HASH_A') 178 | hash_b = self._hash(filename, 'HASH_B') 179 | for entry in self.hash_table: 180 | if (entry.hash_a == hash_a and entry.hash_b == hash_b): 181 | return entry 182 | 183 | def read_file(self, filename, force_decompress=False): 184 | """Read a file from the MPQ archive.""" 185 | 186 | def decompress(data): 187 | """Read the compression type and decompress file data.""" 188 | compression_type = ord(data[0:1]) 189 | if compression_type == 0: 190 | return data 191 | elif compression_type == 2: 192 | return zlib.decompress(data[1:], 15) 193 | elif compression_type == 16: 194 | return bz2.decompress(data[1:]) 195 | else: 196 | raise RuntimeError("Unsupported compression type.") 197 | 198 | hash_entry = self.get_hash_table_entry(filename) 199 | if hash_entry is None: 200 | return None 201 | block_entry = self.block_table[hash_entry.block_table_index] 202 | 203 | # Read the block. 204 | if block_entry.flags & MPQ_FILE_EXISTS: 205 | if block_entry.archived_size == 0: 206 | return None 207 | 208 | offset = block_entry.offset + self.header['offset'] 209 | self.file.seek(offset) 210 | file_data = self.file.read(block_entry.archived_size) 211 | 212 | if block_entry.flags & MPQ_FILE_ENCRYPTED: 213 | raise NotImplementedError("Encryption is not supported yet.") 214 | 215 | if not block_entry.flags & MPQ_FILE_SINGLE_UNIT: 216 | # File consists of many sectors. They all need to be 217 | # decompressed separately and united. 218 | sector_size = 512 << self.header['sector_size_shift'] 219 | sectors = block_entry.size // sector_size + 1 220 | if block_entry.flags & MPQ_FILE_SECTOR_CRC: 221 | crc = True 222 | sectors += 1 223 | else: 224 | crc = False 225 | positions = struct.unpack('<%dI' % (sectors + 1), 226 | file_data[:4*(sectors+1)]) 227 | result = BytesIO() 228 | sector_bytes_left = block_entry.size 229 | for i in range(len(positions) - (2 if crc else 1)): 230 | sector = file_data[positions[i]:positions[i+1]] 231 | if (block_entry.flags & MPQ_FILE_COMPRESS and 232 | (force_decompress or sector_bytes_left > len(sector))): 233 | sector = decompress(sector) 234 | 235 | sector_bytes_left -= len(sector) 236 | result.write(sector) 237 | file_data = result.getvalue() 238 | else: 239 | # Single unit files only need to be decompressed, but 240 | # compression only happens when at least one byte is gained. 241 | if (block_entry.flags & MPQ_FILE_COMPRESS and 242 | (force_decompress or block_entry.size > block_entry.archived_size)): 243 | file_data = decompress(file_data) 244 | 245 | return file_data 246 | 247 | def extract(self): 248 | """Extract all the files inside the MPQ archive in memory.""" 249 | if self.files: 250 | return dict((f, self.read_file(f)) for f in self.files) 251 | else: 252 | raise RuntimeError("Can't extract whole archive without listfile.") 253 | 254 | def extract_to_disk(self): 255 | """Extract all files and write them to disk.""" 256 | archive_name, extension = os.path.splitext(os.path.basename(self.file.name)) 257 | if not os.path.isdir(os.path.join(os.getcwd(), archive_name)): 258 | os.mkdir(archive_name) 259 | os.chdir(archive_name) 260 | for filename, data in self.extract().items(): 261 | f = open(filename, 'wb') 262 | f.write(data or b'') 263 | f.close() 264 | 265 | def extract_files(self, *filenames): 266 | """Extract given files from the archive to disk.""" 267 | for filename in filenames: 268 | data = self.read_file(filename) 269 | f = open(filename, 'wb') 270 | f.write(data or b'') 271 | f.close() 272 | 273 | def print_headers(self): 274 | print("MPQ archive header") 275 | print("------------------") 276 | for key, value in self.header.items(): 277 | if key == "user_data_header": 278 | continue 279 | print("{0:30} {1!r}".format(key, value)) 280 | if self.header.get('user_data_header'): 281 | print() 282 | print("MPQ user data header") 283 | print("--------------------") 284 | for key, value in self.header['user_data_header'].items(): 285 | print("{0:30} {1!r}".format(key, value)) 286 | print() 287 | 288 | def print_hash_table(self): 289 | print("MPQ archive hash table") 290 | print("----------------------") 291 | print(" Hash A Hash B Locl Plat BlockIdx") 292 | for entry in self.hash_table: 293 | print('{0:0>8X} {1:0>8X} {2:0>4X} {3:0>4X} {4:0>8X}'.format(*entry)) 294 | print() 295 | 296 | def print_block_table(self): 297 | print("MPQ archive block table") 298 | print("-----------------------") 299 | print(" Offset ArchSize RealSize Flags") 300 | for entry in self.block_table: 301 | print('{0:0>8X} {1:>8} {2:>8} {3:>8X}'.format(*entry)) 302 | print() 303 | 304 | def print_files(self): 305 | if self.files: 306 | print("Files") 307 | print("-----") 308 | width = max(len(name) for name in self.files) + 2 309 | for filename in self.files: 310 | hash_entry = self.get_hash_table_entry(filename) 311 | block_entry = self.block_table[hash_entry.block_table_index] 312 | print("{0:{width}} {1:>8} bytes".format(filename.decode(), 313 | block_entry.size, 314 | width=width)) 315 | 316 | def _hash(self, string, hash_type): 317 | """Hash a string using MPQ's hash function.""" 318 | hash_types = { 319 | 'TABLE_OFFSET': 0, 320 | 'HASH_A': 1, 321 | 'HASH_B': 2, 322 | 'TABLE': 3 323 | } 324 | seed1 = 0x7FED7FED 325 | seed2 = 0xEEEEEEEE 326 | 327 | for ch in string.upper(): 328 | if not isinstance(ch, int): ch = ord(ch) 329 | value = self.encryption_table[(hash_types[hash_type] << 8) + ch] 330 | seed1 = (value ^ (seed1 + seed2)) & 0xFFFFFFFF 331 | seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3 & 0xFFFFFFFF 332 | 333 | return seed1 334 | 335 | def _decrypt(self, data, key): 336 | """Decrypt hash or block table or a sector.""" 337 | seed1 = key 338 | seed2 = 0xEEEEEEEE 339 | result = BytesIO() 340 | 341 | for i in range(len(data) // 4): 342 | seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)] 343 | seed2 &= 0xFFFFFFFF 344 | value = struct.unpack("> 0x0B) 348 | seed1 &= 0xFFFFFFFF 349 | seed2 = value + seed2 + (seed2 << 5) + 3 & 0xFFFFFFFF 350 | 351 | result.write(struct.pack("> not found in MPQ archives.") 35 | return None 36 | 37 | def extract_files(self, dir, filenames, force_decompress=False): 38 | """ Read the latest version of the files from loaded archives and directories and 39 | extract them to provided working directory. """ 40 | 41 | result = False 42 | for filename in filenames: 43 | file = self.read_file(filename, force_decompress) 44 | if not file: 45 | continue 46 | 47 | abs_path = os.path.join(dir, filename) 48 | local_dir = os.path.dirname(abs_path) 49 | 50 | if not os.path.exists(local_dir): 51 | os.makedirs(local_dir) 52 | 53 | f = open(abs_path, 'wb') 54 | f.write(file or b'') 55 | f.close() 56 | 57 | result = True 58 | 59 | return result 60 | 61 | def extract_textures_as_png(self, dir, filenames, force_decompress=False): 62 | """ Read the latest version of the texture files from loaded archives and directories and 63 | extract them to current working directory as PNG images. """ 64 | if self.converter: 65 | blp_paths = [] 66 | 67 | for filename in filenames: 68 | abs_path = os.path.join(dir, filename) 69 | if not os.path.exists(os.path.splitext(abs_path)[0] + ".png"): 70 | file = self.read_file(filename, force_decompress) 71 | if not file: 72 | continue 73 | local_dir = os.path.dirname(abs_path) 74 | 75 | if not os.path.exists(local_dir): 76 | os.makedirs(local_dir) 77 | 78 | f = open(abs_path, 'wb') 79 | f.write(file or b'') 80 | f.close() 81 | 82 | blp_paths.append(abs_path) 83 | 84 | self.converter.convert(blp_paths) 85 | 86 | for blp_path in blp_paths: 87 | os.remove(blp_path) 88 | 89 | else: 90 | print("\nPNG texture extraction failed. No converter executable specified or found") 91 | 92 | @staticmethod 93 | def list_game_data_paths(path): 94 | """List files and directories in a directory that correspond to WoW patch naming rules.""" 95 | dir_files = [] 96 | for f in os.listdir(path): 97 | cur_path = os.path.join(path, f) 98 | 99 | if os.path.isfile(cur_path) \ 100 | and os.path.splitext(f)[1].lower() == '.mpq' \ 101 | or not os.path.isfile(cur_path) \ 102 | and re.match(r'patch-\w.mpq', f.lower()): 103 | dir_files.append(cur_path) 104 | 105 | map(lambda x: x.lower(), dir_files) 106 | 107 | dir_files.sort(key=lambda s: os.path.splitext(s)[0]) 108 | 109 | return dir_files 110 | 111 | @staticmethod 112 | def is_wow_path_valid(wow_path): 113 | """Check if a given path is a path to WoW client.""" 114 | if wow_path and os.path.exists(os.path.join(wow_path, "Wow.exe")): 115 | return True 116 | 117 | return False 118 | 119 | @staticmethod 120 | def open_game_resources(wow_path): 121 | """Open game resources and store links to them in memory""" 122 | 123 | print("\nProcessing available game resources of client: " + wow_path) 124 | start_time = time.time() 125 | 126 | if WoWFileData.is_wow_path_valid(wow_path): 127 | data_packages = WoWFileData.list_game_data_paths(os.path.join(wow_path, "Data\\")) 128 | resource_map = [] 129 | 130 | for package in data_packages: 131 | if os.path.isfile(package): 132 | resource_map.append((mpyq.MPQArchive(package, listfile=False), True)) 133 | print("\nLoaded MPQ: " + os.path.basename(package)) 134 | else: 135 | resource_map.append((package, False)) 136 | print("\nLoaded folder patch: " + os.path.basename(package)) 137 | 138 | print("\nDone initializing data packages.") 139 | print("Total loading time: ", time.strftime("%M minutes %S seconds", time.gmtime(time.time() - start_time))) 140 | return resource_map 141 | else: 142 | print("\nPath to World of Warcraft is empty or invalid. Failed to load game data.") 143 | return None 144 | 145 | class BLPConverter: 146 | def __init__(self, toolPath): 147 | if os.path.exists(toolPath): 148 | self.toolPath = toolPath 149 | print("\nFound BLP Converter executable: " + toolPath) 150 | else: 151 | raise Exception("\nNo BLPConverter found at given path: " + toolPath) 152 | 153 | def convert(self, filepaths, alwaysReplace = False): 154 | init_length = len(self.toolPath) + 4 155 | init_command = self.toolPath 156 | cur_length = 0 157 | cur_args = [] 158 | 159 | for filepath in filepaths: 160 | if alwaysReplace or not os.path.exists(os.path.splitext(filepath)[0] + ".png"): 161 | length = len(filepath) 162 | 163 | if 2047 - (cur_length + init_length) < length + 2: 164 | final_command = [init_command, '/M'] 165 | final_command.extend(cur_args) 166 | if subprocess.call(final_command): 167 | raise Exception("\nBLP convertion failed.") 168 | cur_length = 0 169 | cur_args = [] 170 | 171 | cur_length += length + 3 172 | cur_args.append(filepath) 173 | 174 | if cur_length: 175 | final_command = [init_command, '/M'] 176 | final_command.extend(cur_args) 177 | if subprocess.call(final_command): 178 | raise Exception("\nBLP convertion failed.") 179 | 180 | 181 | class WOW_FILESYSTEM_LOAD_OP(bpy.types.Operator): 182 | bl_idname = 'scene.load_wow_filesystem' 183 | bl_label = 'Load WoW filesystem' 184 | bl_description = 'Establish connection to World of Warcraft client files' 185 | bl_options = {'REGISTER'} 186 | 187 | def execute(self, context): 188 | 189 | if hasattr(bpy, "wow_game_data"): 190 | 191 | delattr(bpy, "wow_game_data") 192 | self.report({'INFO'}, "WoW game data is unloaded.") 193 | 194 | else: 195 | 196 | preferences = bpy.context.user_preferences.addons.get("io_scene_wmo").preferences 197 | 198 | bpy.wow_game_data = WoWFileData(preferences.wow_path, preferences.blp_path) 199 | 200 | if not bpy.wow_game_data.files: 201 | self.report({'ERROR'}, "WoW game data is not loaded. Check settings.") 202 | return {'CANCELLED'} 203 | 204 | self.report({'INFO'}, "WoW game data is loaded.") 205 | 206 | return {'FINISHED'} 207 | -------------------------------------------------------------------------------- /io_scene_wmo/wmo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WowDevTools/Blender-WMO-import-export-scripts/f0954b16190286a5ac1fea9967d7f0ed3fddd820/io_scene_wmo/wmo/__init__.py -------------------------------------------------------------------------------- /io_scene_wmo/wmo/bsp_tree.py: -------------------------------------------------------------------------------- 1 | from . import wmo_format 2 | from .wmo_format import * 3 | 4 | from . import collision 5 | from .collision import * 6 | 7 | import mathutils 8 | from mathutils import * 9 | 10 | import sys 11 | 12 | 13 | class BSPTree: 14 | def __init__(self): 15 | self.Nodes = [] 16 | self.Faces = [] 17 | pass 18 | 19 | # split box in two smaller, at dist calculated internally 20 | def split_box(self, box, facesInBox, vertices, indices, axis): 21 | # compute average of vertice positions 22 | """count = 0 23 | sum = 0 24 | for iFace in range(len(facesInBox)): 25 | sum += vertices[indices[facesInBox[iFace] * 3]][axis] 26 | sum += vertices[indices[facesInBox[iFace] * 3 + 1]][axis] 27 | sum += vertices[indices[facesInBox[iFace] * 3 + 2]][axis] 28 | count += 1 29 | splitDist = sum / count 30 | 31 | # if split is out of box, just split in half 32 | if(splitDist <= box[0][axis] or splitDist >= box[1][axis]):""" 33 | split_dist = (box[0][axis] + box[1][axis]) / 2 34 | 35 | new_box1 = (Vector((box[0][0], box[0][1], box[0][2])), Vector((box[1][0], box[1][1], box[1][2]))) 36 | new_box1[1][axis] = split_dist 37 | 38 | new_box2 = (Vector((box[0][0], box[0][1], box[0][2])), Vector((box[1][0], box[1][1], box[1][2]))) 39 | new_box2[0][axis] = split_dist 40 | 41 | # split dist absolute coordinate on split axis 42 | # ret_splitDist = splitDist - ((box[0][axis] + box[1][axis]) / 2) 43 | return split_dist, new_box1, new_box2 44 | 45 | # return index of add 46 | def add_node(self, box, faces_in_box, vertices, indices, max_face_count): 47 | 48 | node = BSP_Node() 49 | 50 | i_node = len(self.Nodes) 51 | self.Nodes.append(node) 52 | 53 | # part contain less than 30 polygons, lets end this, add final node 54 | if len(faces_in_box) <= max_face_count: 55 | node.PlaneType = BSP_PLANE_TYPE.Leaf 56 | node.Children = (-1, -1) 57 | node.NumFaces = len(faces_in_box) 58 | node.FirstFace = len(self.Faces) 59 | node.Dist = 0 60 | 61 | self.Faces.extend(faces_in_box) 62 | return i_node 63 | 64 | # split bigger side 65 | box_size_x = box[1][0] - box[0][0] 66 | box_size_y = box[1][1] - box[0][1] 67 | box_size_z = box[1][2] - box[0][2] 68 | 69 | if box_size_x > box_size_y and box_size_x > box_size_z: 70 | # split on axis X (YZ plane) 71 | plane_type = BSP_PLANE_TYPE.YZ_plane 72 | elif box_size_y > box_size_x and box_size_y > box_size_z: 73 | # split on axis Y (XZ plane) 74 | plane_type = BSP_PLANE_TYPE.XZ_plane 75 | else: 76 | # split on axis Z (XY plane) 77 | plane_type = BSP_PLANE_TYPE.XY_plane 78 | 79 | split_result = self.split_box(box, faces_in_box, vertices, indices, plane_type) 80 | 81 | split_dist = split_result[0] 82 | 83 | child1_box = split_result[1] 84 | child1_faces = [] 85 | 86 | # calculate faces in child1 box 87 | for f in faces_in_box: 88 | tri = (Vector((vertices[indices[f * 3]])), 89 | Vector((vertices[indices[f * 3 + 1]])), 90 | Vector((vertices[indices[f * 3 + 2]]))) 91 | 92 | if collide_box_tri(child1_box, tri): 93 | child1_faces.append(f) 94 | 95 | child2_box = split_result[2] 96 | child2_faces = [] 97 | 98 | # calculate faces in child2 box 99 | for f in faces_in_box: 100 | tri = (Vector((vertices[indices[f * 3]])), 101 | Vector((vertices[indices[f * 3 + 1]])), 102 | Vector((vertices[indices[f * 3 + 2]]))) 103 | 104 | if collide_box_tri(child2_box, tri): 105 | child2_faces.append(f) 106 | 107 | # dont add child if there is no faces inside 108 | if len(child1_faces) == 0: 109 | i_child1 = -1 110 | else: 111 | i_child1 = self.add_node(child1_box, child1_faces, vertices, indices, max_face_count) 112 | 113 | if len(child2_faces) == 0: 114 | i_child2 = -1 115 | else: 116 | i_child2 = self.add_node(child2_box, child2_faces, vertices, indices, max_face_count) 117 | 118 | # node = BSP_Node() 119 | node.PlaneType = plane_type 120 | node.Children = (i_child1, i_child2) 121 | node.NumFaces = 0 122 | node.FirstFace = 0 123 | node.Dist = split_dist 124 | 125 | return i_node 126 | 127 | def GenerateBSP(self, vertices, indices, max_face_count): 128 | resurs_limit = sys.getrecursionlimit() 129 | sys.setrecursionlimit(100000) 130 | 131 | faces = [] 132 | for iFace in range(len(indices) // 3): 133 | faces.append(iFace) 134 | 135 | box = calculate_bounding_box(vertices) 136 | self.add_node(box, faces, vertices, indices, max_face_count) 137 | 138 | sys.setrecursionlimit(resurs_limit) 139 | 140 | -------------------------------------------------------------------------------- /io_scene_wmo/wmo/collision.py: -------------------------------------------------------------------------------- 1 | from mathutils import Vector 2 | 3 | 4 | def proj_overlap(poly1_min, poly1_max, poly2_min, poly2_max): 5 | """ Return true if projections of 2 polygons are overlapping """ 6 | return False if poly1_max < poly2_min or poly2_max < poly1_min else True 7 | 8 | 9 | # return min coordinate and max coordinate of a vertex list in a tuple 10 | def get_min_max(vertList): 11 | min = Vector(vertList[0]) 12 | max = Vector(vertList[0]) 13 | for v in vertList: 14 | if v.x < min.x: 15 | min.x = v.x 16 | elif v.x > max.x: 17 | max.x = v.x 18 | if v.y < min.y: 19 | min.y = v.y 20 | elif v.y > max.y: 21 | max.y = v.y 22 | if v.z < min.z: 23 | min.z = v.z 24 | elif v.z > max.z: 25 | max.z = v.z 26 | return min, max 27 | 28 | 29 | def project_point(pt, v): 30 | """ Return projection of point with given direction vector """ 31 | proj = Vector() 32 | # project on X 33 | if v.y == 0: 34 | l = 0 35 | else: 36 | l = - pt.y / v.y 37 | proj.z = pt.x + l * v.x 38 | # project on Y 39 | if v.z == 0: 40 | l = 0 41 | else: 42 | l = - pt.z / v.z 43 | proj.y = pt.x + l * v.x 44 | # project on Z 45 | proj.x = pt.y + l * v.y 46 | return proj 47 | 48 | 49 | def plane_box_overlap(normal, vert, box): 50 | v_min = Vector() 51 | v_max = Vector() 52 | for q in range(0, 3): 53 | v = vert[q] 54 | if normal[q] > 0.0: 55 | v_min[q] = box[0][q] - v 56 | v_max[q] = box[1][q] - v 57 | else: 58 | v_min[q] = box[1][q] - v 59 | v_max[q] = box[0][q] - v 60 | 61 | return True if normal.dot(v_max) >= 0.0 else False 62 | 63 | 64 | def collide_box_tri(box, triangle): 65 | """ Return True if AABB and triangle overlap """ 66 | 67 | triangle_min_max = get_min_max(triangle) 68 | # check if overlap on box axis 69 | if not proj_overlap(box[0].x, box[1].x, triangle_min_max[0].x, triangle_min_max[1].x) \ 70 | or not proj_overlap(box[0].y, box[1].y, triangle_min_max[0].y, triangle_min_max[1].y) \ 71 | or not proj_overlap(box[0].z, box[1].z, triangle_min_max[0].z, triangle_min_max[1].z): 72 | return False 73 | 74 | pt_box = [ 75 | Vector(box[0].xyz), 76 | Vector((box[0].x, box[1].y, box[0].z)), 77 | Vector((box[1].x, box[1].y, box[0].z)), 78 | Vector((box[1].x, box[0].y, box[0].z)), 79 | Vector(box[1].xyz), 80 | Vector((box[0].x, box[1].y, box[1].z)), 81 | Vector((box[1].x, box[1].y, box[1].z)), 82 | Vector((box[1].x, box[0].y, box[1].z)) 83 | ] 84 | 85 | def check_overlaps(projected_box_min_max, projected_triangle_min_max): 86 | 87 | if not proj_overlap(projected_box_min_max[0].x, 88 | projected_box_min_max[1].x, 89 | projected_triangle_min_max[0].x, 90 | projected_triangle_min_max[1].x) \ 91 | or not proj_overlap(projected_box_min_max[0].y, 92 | projected_box_min_max[1].y, 93 | projected_triangle_min_max[0].y, 94 | projected_triangle_min_max[1].y) \ 95 | or not proj_overlap(projected_box_min_max[0].z, 96 | projected_box_min_max[1].z, 97 | projected_triangle_min_max[0].z, 98 | projected_triangle_min_max[1].z): 99 | return True 100 | 101 | return False 102 | 103 | # project on edge 1 axis 104 | E0 = triangle[1] - triangle[0] 105 | pt_box_projected = [] 106 | pt_triangle_projected = [] 107 | 108 | for pt in pt_box: 109 | pt_box_projected.append(project_point(pt, E0)) 110 | for pt in triangle: 111 | pt_triangle_projected.append(project_point(pt, E0)) 112 | 113 | if check_overlaps(get_min_max(pt_box_projected), get_min_max(pt_triangle_projected)): 114 | return False 115 | 116 | # project on edge 2 axis 117 | E1 = triangle[2] - triangle[1] 118 | pt_box_projected = [] 119 | pt_triangle_projected = [] 120 | 121 | for pt in pt_box: 122 | pt_box_projected.append(project_point(pt, E1)) 123 | for pt in triangle: 124 | pt_triangle_projected.append(project_point(pt, E1)) 125 | 126 | if check_overlaps(get_min_max(pt_box_projected), get_min_max(pt_triangle_projected)): 127 | return False 128 | 129 | # project on edge 3 axis 130 | E2 = triangle[0] - triangle[2] 131 | pt_box_projected = [] 132 | pt_triangle_projected = [] 133 | for pt in pt_box: 134 | pt_box_projected.append(project_point(pt, E2)) 135 | for pt in triangle: 136 | pt_triangle_projected.append(project_point(pt, E2)) 137 | 138 | if check_overlaps(get_min_max(pt_box_projected), get_min_max(pt_triangle_projected)) \ 139 | or not plane_box_overlap(E0.cross(E1), triangle[0], box): 140 | return False 141 | 142 | return True 143 | 144 | 145 | def calculate_bounding_box(vertices): 146 | corner1 = Vector(vertices[0]) 147 | corner2 = Vector(vertices[0]) 148 | for v in vertices: 149 | if v[0] < corner1[0]: 150 | corner1[0] = v[0] 151 | elif v[0] > corner2[0]: 152 | corner2[0] = v[0] 153 | if v[1] < corner1[1]: 154 | corner1[1] = v[1] 155 | elif v[1] > corner2[1]: 156 | corner2[1] = v[1] 157 | if v[2] < corner1[2]: 158 | corner1[2] = v[2] 159 | elif v[2] > corner2[2]: 160 | corner2[2] = v[2] 161 | return corner1, corner2 -------------------------------------------------------------------------------- /io_scene_wmo/wmo/export_wmo.py: -------------------------------------------------------------------------------- 1 | from .wmo_file import WMOFile 2 | from .wmo_group import WMOGroupFile 3 | 4 | import bpy 5 | import time 6 | 7 | 8 | def export_wmo_from_blender_scene(filepath, autofill_textures, export_selected): 9 | """ Export WoW WMO object from Blender scene to files """ 10 | 11 | start_time = time.time() 12 | 13 | # bpy.ops.scene.wow_wmo_validate_scene() 14 | # print("\nScene successfully validated") 15 | 16 | wmo = WMOFile(filepath) 17 | 18 | wmo.bl_scene_objects.build_references(export_selected) 19 | 20 | wmo.groups = list([WMOGroupFile(wmo) for _ in wmo.bl_scene_objects.groups]) 21 | 22 | wmo.save_doodad_sets() 23 | 24 | # temporary unlink doodad sets to increase performance 25 | for set in wmo.bl_scene_objects.doodad_sets: 26 | for doodad in set[1]: 27 | doodad.use_fake_user = True 28 | bpy.context.scene.objects.unlink(doodad) 29 | 30 | wmo.save_lights() 31 | wmo.save_liquids() 32 | wmo.save_fogs() 33 | 34 | def restore_doodads(): 35 | for set in wmo.bl_scene_objects.doodad_sets: 36 | for doodad in set[1]: 37 | bpy.context.scene.objects.link(doodad) 38 | doodad.use_fake_user = False 39 | 40 | try: 41 | wmo.save_portals() 42 | 43 | print("\n\n### Saving WMO groups ###") 44 | g_start_time = time.time() 45 | 46 | for index, group in enumerate(wmo.groups): 47 | obj = wmo.bl_scene_objects.groups[index] 48 | proxy_obj = obj.copy() 49 | proxy_obj.data = obj.data.copy() 50 | bpy.context.scene.objects.link(proxy_obj) 51 | try: 52 | group.save(obj, proxy_obj, autofill_textures) 53 | except Exception as exception: 54 | bpy.data.objects.remove(proxy_obj, do_unlink=True) 55 | raise exception 56 | else: 57 | bpy.data.objects.remove(proxy_obj, do_unlink=True) 58 | 59 | print("\nDone saving groups. " 60 | "\nTotal saving time: ", time.strftime("%M minutes %S seconds", time.gmtime(time.time() - g_start_time))) 61 | 62 | wmo.save_root_header() 63 | 64 | except Exception as exception: 65 | restore_doodads() 66 | wmo.bl_scene_objects.clear_references() 67 | raise exception 68 | else: 69 | restore_doodads() 70 | wmo.bl_scene_objects.clear_references() 71 | 72 | wmo.write() 73 | 74 | print("\nExport finished successfully. " 75 | "\nTotal export time: ", time.strftime("%M minutes %S seconds\a", time.gmtime(time.time() - start_time))) 76 | -------------------------------------------------------------------------------- /io_scene_wmo/wmo/import_wmo.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import time 4 | 5 | from .wmo_file import WMOFile 6 | 7 | 8 | def import_wmo_to_blender_scene(filepath, load_textures, import_doodads, group_objects): 9 | """ Read and import WoW WMO object to Blender scene""" 10 | 11 | start_time = time.time() 12 | 13 | wmo = WMOFile(filepath) 14 | wmo.read() 15 | 16 | print("\n\n### Importing WMO components ###") 17 | 18 | game_data = None 19 | 20 | if load_textures or import_doodads: 21 | game_data = getattr(bpy, "wow_game_data", None) 22 | 23 | if not game_data: 24 | print("\n\n### Loading game data ###") 25 | bpy.ops.scene.load_wow_filesystem() 26 | game_data = bpy.wow_game_data 27 | 28 | if game_data.files: 29 | if load_textures: 30 | print("\n\n### Extracting textures ###") 31 | game_data.extract_textures_as_png(os.path.dirname(filepath), wmo.motx.get_all_strings()) 32 | else: 33 | print("\nFailed to load textures because game data was not loaded.") 34 | 35 | # group objects if required 36 | parent = None 37 | if group_objects: 38 | bpy.ops.object.empty_add(type='PLAIN_AXES', location=(0, 0, 0)) 39 | parent = bpy.context.scene.objects.active 40 | parent.name = wmo.display_name + ".wmo" 41 | wmo.parent = parent 42 | 43 | # load all materials in root file 44 | wmo.load_materials() 45 | 46 | # load all WMO components 47 | wmo.load_lights() 48 | wmo.load_properties() 49 | wmo.load_fogs() 50 | 51 | print("\n\n### Importing WMO groups ###") 52 | 53 | for group in wmo.groups: 54 | obj_name = wmo.mogn.get_string(group.mogp.GroupNameOfs) 55 | print("\nImporting group <<{}>>".format(obj_name)) 56 | group.load_object(obj_name, import_doodads) 57 | 58 | wmo.load_portals() 59 | 60 | print("\n\n### Importing WMO doodad sets ###") 61 | 62 | if import_doodads and game_data.files: 63 | wmo.load_doodads(os.path.dirname(filepath), game_data) 64 | else: 65 | wmo.load_doodads() 66 | 67 | print("\nDone importing WMO. \nTotal import time: ", 68 | time.strftime("%M minutes %S seconds.\a", time.gmtime(time.time() - start_time))) 69 | 70 | return parent 71 | -------------------------------------------------------------------------------- /io_scene_wmo/wmo/ui/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WowDevTools/Blender-WMO-import-export-scripts/f0954b16190286a5ac1fea9967d7f0ed3fddd820/io_scene_wmo/wmo/ui/__init__.py -------------------------------------------------------------------------------- /io_scene_wmo/wmo/ui/enums.py: -------------------------------------------------------------------------------- 1 | shader_enum = [ 2 | ('0', "Diffuse", ""), ('1', "Specular", ""), ('2', "Metal", ""), 3 | ('3', "Env", ""), ('4', "Opaque", ""), ('5', "EnvMetal", ""), 4 | ('6', "TwoLayerDiffuse", ""), ('7', "TwoLayerEnvMetal", ""), ('8', "TwoLayerTerrain", ""), 5 | ('9', "DiffuseEmissive", ""), ('10', "Tangent", ""), ('11', "MaskedEnvMetal", ""), 6 | ('12', "EnvMetalEmissive", ""), ('13', "TwoLayerDiffuseOpaque", ""), ('14', "TwoLayerDiffuseEmissive", "") 7 | ] 8 | 9 | terrain_type_enum = [ 10 | ('0', "Dirt", ""), ('1', "Metallic", ""), ('2', "Stone", ""), 11 | ('3', "Snow", ""), ('4', "Wood", ""), ('5', "Grass", ""), 12 | ('6', "Leaves", ""), ('7', "Sand", ""), ('8', "Soggy", ""), 13 | ('9', "Dusty Grass", ""), ('10', "None", ""), ('11', "Water", "") 14 | ] 15 | 16 | blending_enum = [ 17 | ('0', "Blend_Opaque", ""), ('1', "Blend_AlphaKey", ""), ('2', "Blend_Alpha", ""), 18 | ('3', "Blend_Add", ""), ('4', "Blend_Mod", ""), ('5', "Blend_Mod2x", ""), 19 | ('6', "Blend_ModAdd", ""), ('7', "Blend_InvSrcAlphaAdd", ""), ('8', "Blend_InvSrcAlphaOpaque", ""), 20 | ('9', "Blend_SrcAlphaOpaque", ""), ('10', "Blend_NoAlphaAdd", ""), ('11', "Blend_ConstantAlpha", "") 21 | ] 22 | 23 | material_flag_enum = [ 24 | ("1", "Unlit", "Disable lighting", 'PMARKER', 0x1), 25 | ("2", "Unfogged", "Disable fog", 'FORCE_TURBULENCE', 0x2), 26 | ("4", "Two-sided", "Render from both sides", 'ARROW_LEFTRIGHT', 0x4), 27 | ("8", "Exterior light", "Ignore local WMO lighting, use world lighting instead", 'PMARKER_SEL', 0x8), 28 | ("16", "Night Glow", "Used for windows to glow at nighttime", 'PMARKER_ACT', 0x10), 29 | ("32", "Window", "Unknown, used for windows", 'MOD_WIREFRAME', 0x20), 30 | ("64", "Clamp_S", "Force texture to use clamp _s adressing", 'TRIA_RIGHT', 0x40), 31 | ("128", "Clamp_T", "Force texture to use clamp _t adressing", 'TRIA_RIGHT', 0x80) 32 | ] 33 | 34 | group_flag_enum = [ 35 | ('0', "Vertex color", "Check if you need vertex color in this group", 'COLOR', 0x1), 36 | ('1', "No local lighting", "Use world-defined lighting in a group", 'PMARKER_SEL', 0x2), 37 | ('2', "Always draw", "Always draw the model. Disable portal-based geometry culling", 'MOD_PARTICLES', 0x4), 38 | ('3', "Mounts allowed", "Allow mounts in this indoor group", 'RESTRICT_VIEW_OFF', 0x8), 39 | ('4', "Use Skybox", "Display WMO skybox in this indoor group", 'WIRE', 0x10) 40 | ] 41 | 42 | place_type_enum = [('8', "Outdoor", "", 'CURVE_NCIRCLE', 0), ('8192', "Indoor", "", 'FORCE_FORCE', 1)] 43 | 44 | liquid_type_enum = [ 45 | ('0', "No liquid", ""), ('1', "Water", ""), ('2', "Ocean", ""), 46 | ('3', "Magma", ""), ('4', "Slime", ""), ('5', "Slow Water", ""), 47 | ('6', "Slow Ocean", ""), ('7', "Slow Magma", ""), ('8', "Slow Slime", ""), 48 | ('9', "Fast Water", ""), ('10', "Fast Ocean", ""), ('11', "Fast Magma", ""), 49 | ('12', "Fast Slime", ""), ('13', "WMO Water", ""), ('14', "WMO Ocean", ""), 50 | ('15', "Green Lava", ""), ('17', "WMO Water - Interior", ""), ('19', "WMO Magma", ""), 51 | ('20', "WMO Slime", ""), ('21', "Naxxramas - Slime", ""), ('41', "Coilfang Raid - Water", ""), 52 | ('61', "Hyjal Past - Water", ""), ('81', "Lake Wintergrasp - Water", ""), ('100', "Basic Procedural Water", ""), 53 | ('121', "CoA Black - Magma", ""), ('141', "Chamber Magma", ""), ('181', "Orange Slime", "") 54 | ] 55 | 56 | portal_dir_alg_enum = [ 57 | ("0", "Auto", "", 'MONKEY', 0), 58 | ("1", "Positive", "", 'ZOOMIN', 1), 59 | ("2", "Negative", "", 'ZOOMOUT', 2) 60 | ] 61 | 62 | root_flags_enum = [ 63 | ("0", "Auto Attenuation", "Attenuate light on vertices based on distance from portal", 'MOD_MIRROR', 0x1), 64 | ("1", "Lighten Indoor", "Lighten up all indoor groups automatically", 'LAMP_SUN', 0x2), 65 | ("2", "Use Ambient", "Use ambient lighting inside indoor groups", 'PMARKER_ACT', 0x4) 66 | ] 67 | 68 | light_type_enum = [ 69 | ('0', "Omni", ""), ('1', "Spot", ""), 70 | ('2', "Direct", ""), ('3', "Ambient", "") 71 | ] 72 | -------------------------------------------------------------------------------- /io_scene_wmo/wmo/ui/panels.py: -------------------------------------------------------------------------------- 1 | from .enums import * 2 | from ...idproperty import idproperty 3 | 4 | import bpy 5 | 6 | 7 | ############################### 8 | ## Root properties 9 | ############################### 10 | 11 | class WoWRootPanel(bpy.types.Panel): 12 | bl_space_type = "PROPERTIES" 13 | bl_region_type = "WINDOW" 14 | bl_context = "scene" 15 | bl_label = "WoW Root" 16 | 17 | def draw_header(self, context): 18 | layout = self.layout 19 | 20 | def draw(self, context): 21 | layout = self.layout 22 | col = layout.column() 23 | col.prop(context.scene.WoWRoot, "Flags") 24 | col.separator() 25 | 26 | if "2" in context.scene.WoWRoot.Flags: 27 | col.prop(context.scene.WoWRoot, "AmbientColor") 28 | 29 | col.separator() 30 | 31 | col.prop(context.scene.WoWRoot, "SkyboxPath") 32 | col.prop(context.scene.WoWRoot, "WMOid") 33 | 34 | @classmethod 35 | def poll(cls, context): 36 | return (context.scene is not None) 37 | 38 | 39 | class MODS_Set(bpy.types.PropertyGroup): 40 | Name = bpy.props.StringProperty() 41 | StartDoodad = bpy.props.IntProperty() 42 | nDoodads = bpy.props.IntProperty() 43 | Padding = bpy.props.IntProperty() 44 | 45 | 46 | class MODN_String(bpy.types.PropertyGroup): 47 | Ofs = bpy.props.IntProperty() 48 | String = bpy.props.StringProperty() 49 | 50 | 51 | class MODD_Definition(bpy.types.PropertyGroup): 52 | NameOfs = bpy.props.IntProperty() 53 | Flags = bpy.props.IntProperty() 54 | Position = bpy.props.FloatVectorProperty() 55 | Rotation = bpy.props.FloatVectorProperty() 56 | Tilt = bpy.props.FloatProperty() 57 | Scale = bpy.props.FloatProperty() 58 | Color = bpy.props.FloatVectorProperty() 59 | ColorAlpha = bpy.props.FloatProperty() 60 | 61 | 62 | class WowRootPropertyGroup(bpy.types.PropertyGroup): 63 | 64 | MODS_Sets = bpy.props.CollectionProperty(type=MODS_Set) 65 | MODN_StringTable = bpy.props.CollectionProperty(type=MODN_String) 66 | MODD_Definitions = bpy.props.CollectionProperty(type=MODD_Definition) 67 | 68 | Flags = bpy.props.EnumProperty( 69 | name="Root flags", 70 | description="WoW WMO root flags", 71 | items=root_flags_enum, 72 | options={"ENUM_FLAG"} 73 | ) 74 | 75 | AmbientColor = bpy.props.FloatVectorProperty( 76 | name="Ambient Color", 77 | subtype='COLOR', 78 | default=(1, 1, 1, 1), 79 | size=4, 80 | min=0.0, 81 | max=1.0 82 | ) 83 | 84 | SkyboxPath = bpy.props.StringProperty( 85 | name="SkyboxPath", 86 | description="Skybox for WMO (.MDX)", 87 | default='', 88 | ) 89 | 90 | WMOid = bpy.props.IntProperty( 91 | name="WMO DBC ID", 92 | description="Used in WMOAreaTable (optional)", 93 | default=0, 94 | ) 95 | 96 | 97 | def RegisterWowRootProperties(): 98 | bpy.types.Scene.WoWRoot = bpy.props.PointerProperty(type=WowRootPropertyGroup) 99 | 100 | 101 | def UnregisterWowRootProperties(): 102 | bpy.types.Scene.WoWRoot = None 103 | 104 | 105 | ############################### 106 | ## Doodads 107 | ############################### 108 | 109 | class WoWDoodadPanel(bpy.types.Panel): 110 | bl_space_type = "PROPERTIES" 111 | bl_region_type = "WINDOW" 112 | bl_context = "object" 113 | bl_label = "WoW Doodad" 114 | 115 | def draw_header(self, context): 116 | layout = self.layout 117 | 118 | def draw(self, context): 119 | layout = self.layout 120 | layout.prop(context.object.WoWDoodad, "Path") 121 | layout.prop(context.object.WoWDoodad, "Color") 122 | 123 | col = layout.column() 124 | col.label("Flags:") 125 | col.prop(context.object.WoWDoodad, "Flags") 126 | layout.enabled = context.object.WoWDoodad.Enabled 127 | 128 | @classmethod 129 | def poll(cls, context): 130 | return (context.object is not None 131 | and context.object.WoWDoodad.Enabled 132 | and isinstance(context.object.data, bpy.types.Mesh)) 133 | 134 | 135 | class WoWDoodadPropertyGroup(bpy.types.PropertyGroup): 136 | 137 | Path = bpy.props.StringProperty() 138 | 139 | Color = bpy.props.FloatVectorProperty( 140 | name="Color", 141 | subtype='COLOR', 142 | size=4, 143 | default=(1,1,1,1), 144 | min=0.0, 145 | max=1.0 146 | ) 147 | 148 | Flags = bpy.props.EnumProperty( 149 | name ="Doodad flags", 150 | description ="WoW doodad instance flags", 151 | items =[ 152 | ("1" , "Accept Projected Tex.", ""), 153 | ("2", "Adjust lighting", ""), 154 | ("4", "Unknown", ""), 155 | ("8", "Unknown", "")], 156 | options={"ENUM_FLAG"} 157 | ) 158 | 159 | Enabled = bpy.props.BoolProperty( 160 | name="", 161 | description="Enable WoW Doodad properties" 162 | ) 163 | 164 | 165 | def RegisterWoWDoodadProperties(): 166 | bpy.types.Object.WoWDoodad = bpy.props.PointerProperty(type=WoWDoodadPropertyGroup) 167 | 168 | 169 | def UnregisterWoWDoodadProperties(): 170 | bpy.types.Object.WoWDoodad = None 171 | 172 | 173 | ############################### 174 | ## Material 175 | ############################### 176 | 177 | class WowMaterialPanel(bpy.types.Panel): 178 | bl_space_type = "PROPERTIES" 179 | bl_region_type = "WINDOW" 180 | bl_context = "material" 181 | bl_label = "WoW Material" 182 | 183 | def draw_header(self, context): 184 | layout = self.layout 185 | self.layout.prop(context.material.WowMaterial, "Enabled") 186 | 187 | def draw(self, context): 188 | layout = self.layout 189 | col = layout.column() 190 | col.prop(context.material.WowMaterial, "Shader") 191 | col.prop(context.material.WowMaterial, "TerrainType") 192 | col.prop(context.material.WowMaterial, "BlendingMode") 193 | 194 | col.separator() 195 | col.prop(context.material.WowMaterial, "Texture1") 196 | col.prop(context.material.WowMaterial, "Texture2") 197 | 198 | col.separator() 199 | col.label("Flags:") 200 | col.prop(context.material.WowMaterial, "Flags") 201 | 202 | layout.prop(context.material.WowMaterial, "EmissiveColor") 203 | layout.prop(context.material.WowMaterial, "DiffColor") 204 | layout.enabled = context.material.WowMaterial.Enabled 205 | 206 | @classmethod 207 | def poll(cls, context): 208 | return context.material is not None 209 | 210 | 211 | class WowMaterialPropertyGroup(bpy.types.PropertyGroup): 212 | 213 | Enabled = bpy.props.BoolProperty( 214 | name="", 215 | description="Enable WoW material properties" 216 | ) 217 | 218 | Flags = bpy.props.EnumProperty( 219 | name="Material flags", 220 | description="WoW material flags", 221 | items=material_flag_enum, 222 | options={"ENUM_FLAG"} 223 | ) 224 | 225 | Shader = bpy.props.EnumProperty( 226 | items=shader_enum, 227 | name="Shader", 228 | description="WoW shader assigned to this material" 229 | ) 230 | 231 | BlendingMode = bpy.props.EnumProperty( 232 | items=blending_enum, 233 | name="Blending", 234 | description="WoW material blending mode" 235 | ) 236 | 237 | Texture1 = bpy.props.StringProperty( 238 | name="Texture 1", 239 | description="Diffuse texture" 240 | ) 241 | 242 | EmissiveColor = bpy.props.FloatVectorProperty( 243 | name="Emissive Color", 244 | subtype='COLOR', 245 | default=(1,1,1,1), 246 | size=4, 247 | min=0.0, 248 | max=1.0 249 | ) 250 | 251 | Texture2 = bpy.props.StringProperty( 252 | name="Texture 2", 253 | description="Environment texture" 254 | ) 255 | 256 | DiffColor = bpy.props.FloatVectorProperty( 257 | name="Diffuse Color", 258 | subtype='COLOR', 259 | default=(1,1,1,1), 260 | size=4, 261 | min=0.0, 262 | max=1.0 263 | ) 264 | 265 | TerrainType = bpy.props.EnumProperty( 266 | items=terrain_type_enum, 267 | name="Terrain Type", 268 | description="Terrain type assigned to this material. Used for producing correct footstep sounds." 269 | ) 270 | 271 | 272 | def RegisterWowMaterialProperties(): 273 | bpy.types.Material.WowMaterial = bpy.props.PointerProperty(type=WowMaterialPropertyGroup) 274 | 275 | def UnregisterWowMaterialProperties(): 276 | bpy.types.Material.WowMaterial = None 277 | 278 | 279 | ############################### 280 | ## Light 281 | ############################### 282 | 283 | class WowLightPanel(bpy.types.Panel): 284 | bl_space_type = "PROPERTIES" 285 | bl_region_type = "WINDOW" 286 | bl_context = "data" 287 | bl_label = "WoW light" 288 | 289 | def draw_header(self, context): 290 | self.layout.prop(context.object.data.WowLight, "Enabled") 291 | 292 | def draw(self, context): 293 | layout = self.layout 294 | self.layout.prop(context.object.data.WowLight, "LightType") 295 | self.layout.prop(context.object.data.WowLight, "UseAttenuation") 296 | self.layout.prop(context.object.data.WowLight, "Color") 297 | self.layout.prop(context.object.data.WowLight, "Intensity") 298 | self.layout.prop(context.object.data.WowLight, "AttenuationStart") 299 | self.layout.prop(context.object.data.WowLight, "AttenuationEnd") 300 | layout.enabled = context.object.data.WowLight.Enabled 301 | 302 | @classmethod 303 | def poll(cls, context): 304 | return (context.object is not None 305 | and context.object.data is not None 306 | and isinstance(context.object.data, bpy.types.Lamp) 307 | ) 308 | 309 | 310 | class WowLightPropertyGroup(bpy.types.PropertyGroup): 311 | 312 | Enabled = bpy.props.BoolProperty( 313 | name="", 314 | description="Enable wow light properties" 315 | ) 316 | 317 | LightType = bpy.props.EnumProperty( 318 | items=light_type_enum, 319 | name="Type", 320 | description="Type of the lamp" 321 | ) 322 | 323 | Type = bpy.props.BoolProperty( 324 | name="Type", 325 | description="Unknown" 326 | ) 327 | 328 | UseAttenuation = bpy.props.BoolProperty( 329 | name="Use attenuation", 330 | description="True if lamp use attenuation" 331 | ) 332 | 333 | Padding = bpy.props.BoolProperty( 334 | name="Padding", 335 | description="True if lamp use Padding" 336 | ) 337 | 338 | Color = bpy.props.FloatVectorProperty( 339 | name="Color", 340 | subtype='COLOR', 341 | default=(1,1,1), 342 | min=0.0, 343 | max=1.0 344 | ) 345 | 346 | Intensity = bpy.props.FloatProperty( 347 | name="Intensity", 348 | description="Intensity of the lamp" 349 | ) 350 | 351 | ColorAlpha = bpy.props.FloatProperty( 352 | name="ColorAlpha", 353 | description="Color alpha", 354 | default=1, 355 | min=0.0, 356 | max=1.0 357 | ) 358 | 359 | AttenuationStart = bpy.props.FloatProperty( 360 | name="Attenuation start", 361 | description="Distance at which light intensity starts to decrease" 362 | ) 363 | 364 | AttenuationEnd = bpy.props.FloatProperty( 365 | name="Attenuation end", 366 | description="Distance at which light intensity reach 0" 367 | ) 368 | 369 | 370 | def RegisterWowLightProperties(): 371 | bpy.types.Lamp.WowLight = bpy.props.PointerProperty(type=WowLightPropertyGroup) 372 | 373 | 374 | def UnregisterWowLightProperties(): 375 | bpy.types.Lamp.WowLight = None 376 | 377 | 378 | ############################### 379 | ## Vertex Info 380 | ############################### 381 | 382 | class WowVertexInfoPanel(bpy.types.Panel): 383 | bl_space_type = "PROPERTIES" 384 | bl_region_type = "WINDOW" 385 | bl_context = "data" 386 | bl_label = "WoW Vertex Info" 387 | 388 | def draw_header(self, context): 389 | layout = self.layout 390 | 391 | def draw(self, context): 392 | layout = self.layout 393 | row = layout.row() 394 | self.layout.prop_search(context.object.WowVertexInfo, "VertexGroup", 395 | context.object, "vertex_groups", text="Collision vertex group" 396 | ) 397 | 398 | self.layout.prop(context.object.WowVertexInfo, "NodeSize", slider=True) 399 | 400 | self.layout.prop_search(context.object.WowVertexInfo, "BatchTypeA", context.object, 401 | "vertex_groups", text="Batch type A vertex group" 402 | ) 403 | 404 | self.layout.prop_search(context.object.WowVertexInfo, "BatchTypeB", 405 | context.object, "vertex_groups", text="Batch type B vertex group" 406 | ) 407 | 408 | self.layout.prop_search(context.object.WowVertexInfo, "Lightmap", 409 | context.object, "vertex_groups", text="Lightmap" 410 | ) 411 | 412 | self.layout.prop_search(context.object.WowVertexInfo, "Blendmap", context.object, 413 | "vertex_groups", text="Blendmap" 414 | ) 415 | 416 | self.layout.prop_search(context.object.WowVertexInfo, "SecondUV", context.object.data, 417 | "uv_textures", text="Second UV" 418 | ) 419 | 420 | @classmethod 421 | def poll(cls, context): 422 | return (context.object is not None 423 | and context.object.data is not None 424 | and isinstance(context.object.data,bpy.types.Mesh) 425 | and context.object.WowWMOGroup.Enabled 426 | ) 427 | 428 | class WowVertexInfoPropertyGroup(bpy.types.PropertyGroup): 429 | VertexGroup = bpy.props.StringProperty() 430 | 431 | NodeSize = bpy.props.IntProperty( 432 | name="Node max size", 433 | description="Max count of faces for a node in bsp tree", 434 | default=2500, min=1, 435 | soft_max=5000 436 | ) 437 | 438 | BatchTypeA = bpy.props.StringProperty() 439 | BatchTypeB = bpy.props.StringProperty() 440 | Lightmap = bpy.props.StringProperty() 441 | Blendmap = bpy.props.StringProperty() 442 | SecondUV = bpy.props.StringProperty() 443 | 444 | def RegisterWowVertexInfoProperties(): 445 | bpy.types.Object.WowVertexInfo = bpy.props.PointerProperty(type=WowVertexInfoPropertyGroup) 446 | 447 | def UnregisterWowVertexInfoProperties(): 448 | bpy.types.Object.WowVertexInfo = None 449 | 450 | 451 | ############################### 452 | ## WMO Group 453 | ############################### 454 | class WowWMOGroupPanel(bpy.types.Panel): 455 | bl_space_type = "PROPERTIES" 456 | bl_region_type = "WINDOW" 457 | bl_context = "object" 458 | bl_label = "WoW WMO Group" 459 | 460 | def draw_header(self, context): 461 | layout = self.layout 462 | self.layout.prop(context.object.WowWMOGroup, "Enabled") 463 | 464 | def draw(self, context): 465 | col = self.layout.column() 466 | col.prop(context.object.WowWMOGroup, "GroupDesc") 467 | 468 | col.separator() 469 | col.label("Flags:") 470 | col.prop(context.object.WowWMOGroup, "PlaceType") 471 | col.prop(context.object.WowWMOGroup, "Flags") 472 | 473 | col.separator() 474 | col.label("Fogs:") 475 | idproperty.layout_id_prop(col, context.object.WowWMOGroup, "Fog1") 476 | idproperty.layout_id_prop(col, context.object.WowWMOGroup, "Fog2") 477 | idproperty.layout_id_prop(col, context.object.WowWMOGroup, "Fog3") 478 | idproperty.layout_id_prop(col, context.object.WowWMOGroup, "Fog4") 479 | 480 | col.separator() 481 | col.prop(context.object.WowWMOGroup, "GroupDBCid") 482 | col.prop(context.object.WowWMOGroup, "LiquidType") 483 | 484 | idproperty.enabled = context.object.WowLiquid.Enabled 485 | self.layout.enabled = context.object.WowWMOGroup.Enabled 486 | 487 | @classmethod 488 | def poll(cls, context): 489 | return (context.object is not None 490 | and context.object.data is not None 491 | and isinstance(context.object.data,bpy.types.Mesh) 492 | and not context.object.WowPortalPlane.Enabled 493 | and not context.object.WowLiquid.Enabled 494 | and not context.object.WowFog.Enabled 495 | and not context.object.WoWDoodad.Enabled 496 | ) 497 | 498 | def fog_validator(ob): 499 | return ob.WowFog.Enabled 500 | 501 | class WowWMOMODRStore(bpy.types.PropertyGroup): 502 | value = bpy.props.IntProperty(name="Doodads Ref") 503 | 504 | class WowWMOPortalRel(bpy.types.PropertyGroup): 505 | id = bpy.props.StringProperty() 506 | 507 | class WowWMOLightRel(bpy.types.PropertyGroup): 508 | id = bpy.props.IntProperty() 509 | 510 | class WowWMODoodadRel(bpy.types.PropertyGroup): 511 | id = bpy.props.IntProperty() 512 | 513 | class WowWMOGroupRelations(bpy.types.PropertyGroup): 514 | """Used for export internally""" 515 | Portals = bpy.props.CollectionProperty(type=WowWMOPortalRel) 516 | Lights = bpy.props.CollectionProperty(type=WowWMOLightRel) 517 | Liquid = bpy.props.StringProperty() 518 | Doodads = bpy.props.CollectionProperty(type=WowWMODoodadRel) 519 | 520 | 521 | class WowWMOGroupPropertyGroup(bpy.types.PropertyGroup): 522 | 523 | GroupDesc = bpy.props.StringProperty(name="Description") 524 | 525 | Enabled = bpy.props.BoolProperty( 526 | name="", 527 | description="Enable wow WMO group properties" 528 | ) 529 | 530 | Flags = bpy.props.EnumProperty( 531 | items=group_flag_enum, 532 | options={'ENUM_FLAG'} 533 | ) 534 | 535 | PlaceType = bpy.props.EnumProperty( 536 | items=place_type_enum, 537 | name="Place Type", 538 | description="Group is indoor or outdoor" 539 | ) 540 | 541 | GroupID = bpy.props.IntProperty( 542 | name="", 543 | description="Group identifier used for export" 544 | ) 545 | 546 | GroupDBCid = bpy.props.IntProperty( 547 | name="DBC Group ID", 548 | description="WMO Group ID in DBC file" 549 | ) 550 | 551 | LiquidType = bpy.props.EnumProperty( 552 | items=liquid_type_enum, 553 | name="LiquidType", 554 | description="Fill this WMO group with selected liquid." 555 | ) 556 | 557 | Fog1 = idproperty.ObjectIDProperty(name="Fog #1", validator=fog_validator) 558 | 559 | Fog2 = idproperty.ObjectIDProperty(name="Fog #2", validator=fog_validator) 560 | 561 | Fog3 = idproperty.ObjectIDProperty(name="Fog #3", validator=fog_validator) 562 | 563 | Fog4 = idproperty.ObjectIDProperty(name="Fog #4", validator=fog_validator) 564 | 565 | 566 | MODR = bpy.props.CollectionProperty(type=WowWMOMODRStore) 567 | 568 | Relations = bpy.props.PointerProperty(type=WowWMOGroupRelations) 569 | 570 | def RegisterWowWMOGroupProperties(): 571 | bpy.types.Object.WowWMOGroup = bpy.props.PointerProperty(type=WowWMOGroupPropertyGroup) 572 | 573 | def UnregisterWowWMOGroupProperties(): 574 | bpy.types.Object.WowWMOGroup = None 575 | 576 | 577 | ############################### 578 | ## Portal plane 579 | ############################### 580 | 581 | class WowPortalPlanePanel(bpy.types.Panel): 582 | bl_space_type = "PROPERTIES" 583 | bl_region_type = "WINDOW" 584 | bl_context = "object" 585 | bl_label = "WoW Portal Plane" 586 | 587 | def draw_header(self, context): 588 | layout = self.layout 589 | self.layout.prop(context.object.WowPortalPlane, "Enabled") 590 | 591 | def draw(self, context): 592 | layout = self.layout 593 | row = layout.row() 594 | 595 | column = layout.column() 596 | idproperty.layout_id_prop(column, context.object.WowPortalPlane, "First") 597 | idproperty.layout_id_prop(column, context.object.WowPortalPlane, "Second") 598 | 599 | col = layout.column() 600 | 601 | col.separator() 602 | col.label("Relation direction:") 603 | col.prop(context.object.WowPortalPlane, "Algorithm", expand=True) 604 | 605 | idproperty.enabled = context.object.WowLiquid.Enabled 606 | layout.enabled = context.object.WowPortalPlane.Enabled 607 | 608 | @classmethod 609 | def poll(cls, context): 610 | return (context.object is not None 611 | and context.object.data is not None 612 | and isinstance(context.object.data,bpy.types.Mesh) 613 | and not context.object.WowWMOGroup.Enabled 614 | and not context.object.WowLiquid.Enabled 615 | and not context.object.WowFog.Enabled 616 | and not context.object.WoWDoodad.Enabled 617 | ) 618 | 619 | def portal_validator(ob): 620 | return ob.type == 'MESH' and ob.WowWMOGroup.Enabled 621 | 622 | class WowPortalPlanePropertyGroup(bpy.types.PropertyGroup): 623 | 624 | Enabled = bpy.props.BoolProperty( 625 | name="", 626 | description="Enable wow WMO group properties" 627 | ) 628 | 629 | First = idproperty.ObjectIDProperty( 630 | name="First group", 631 | validator=portal_validator 632 | ) 633 | 634 | Second = idproperty.ObjectIDProperty( 635 | name="Second group", 636 | validator=portal_validator 637 | ) 638 | 639 | PortalID = bpy.props.IntProperty( 640 | name="Portal's ID", 641 | description="Portal ID" 642 | ) 643 | 644 | Algorithm = bpy.props.EnumProperty( 645 | items=portal_dir_alg_enum, 646 | default="0" 647 | ) 648 | 649 | 650 | def RegisterWowPortalPlaneProperties(): 651 | bpy.types.Object.WowPortalPlane = bpy.props.PointerProperty(type=WowPortalPlanePropertyGroup) 652 | 653 | def UnregisterWowPortalPlaneProperties(): 654 | bpy.types.Object.WowPortalPlane = None 655 | 656 | ############################### 657 | ## Liquid 658 | ############################### 659 | 660 | class WowLiquidPanel(bpy.types.Panel): 661 | bl_space_type = "PROPERTIES" 662 | bl_region_type = "WINDOW" 663 | bl_context = "object" 664 | bl_label = "WoW Liquid" 665 | 666 | def draw_header(self, context): 667 | layout = self.layout 668 | 669 | def draw(self, context): 670 | layout = self.layout 671 | row = layout.row() 672 | self.layout.prop(context.object.WowLiquid, "LiquidType") 673 | self.layout.prop(context.object.WowLiquid, "Color") 674 | 675 | column = layout.column() 676 | idproperty.layout_id_prop(column, context.object.WowLiquid, "WMOGroup") 677 | 678 | idproperty.enabled = context.object.WowLiquid.Enabled 679 | layout.enabled = context.object.WowLiquid.Enabled 680 | 681 | @classmethod 682 | def poll(cls, context): 683 | return (context.object is not None 684 | and context.object.data is not None 685 | and isinstance(context.object.data,bpy.types.Mesh) 686 | and context.object.WowLiquid.Enabled 687 | ) 688 | 689 | def liquid_validator(ob): 690 | for object in bpy.context.scene.objects: 691 | if object.type == 'MESH' and object.WowLiquid.WMOGroup == ob.name: 692 | bpy.ops.render.report_message(message="Test", type=False ) 693 | return False 694 | return ob.WowWMOGroup.Enabled 695 | 696 | class WowLiquidPropertyGroup(bpy.types.PropertyGroup): 697 | 698 | Enabled = bpy.props.BoolProperty( 699 | name="", 700 | description="Enable wow liquid properties", 701 | default=False 702 | ) 703 | 704 | Color = bpy.props.FloatVectorProperty( 705 | name="Color", 706 | subtype='COLOR', 707 | default=(0.08, 0.08, 0.08, 1), 708 | size=4, 709 | min=0.0, 710 | max=1.0 711 | ) 712 | 713 | LiquidType = bpy.props.EnumProperty( 714 | items=liquid_type_enum, 715 | name="Liquid Type", 716 | description="Type of the liquid present in this WMO group" 717 | ) 718 | 719 | WMOGroup = idproperty.ObjectIDProperty( 720 | name="WMO Group", 721 | validator=liquid_validator 722 | ) 723 | 724 | def RegisterWowLiquidProperties(): 725 | bpy.types.Object.WowLiquid = bpy.props.PointerProperty(type=WowLiquidPropertyGroup) 726 | 727 | def UnregisterWowLiquidProperties(): 728 | bpy.types.Object.WowLiquid = None 729 | 730 | 731 | ############################### 732 | ## Fog 733 | ############################### 734 | class WowFogPanel(bpy.types.Panel): 735 | bl_space_type = "PROPERTIES" 736 | bl_region_type = "WINDOW" 737 | bl_context = "object" 738 | bl_label = "WoW Fog" 739 | 740 | def draw_header(self, context): 741 | layout = self.layout 742 | 743 | def draw(self, context): 744 | layout = self.layout 745 | row = layout.row() 746 | layout.enabled = context.object.WowFog.Enabled 747 | self.layout.prop(context.object.WowFog, "IgnoreRadius") 748 | self.layout.prop(context.object.WowFog, "Unknown") 749 | self.layout.prop(context.object.WowFog, "InnerRadius") 750 | self.layout.prop(context.object.WowFog, "EndDist") 751 | self.layout.prop(context.object.WowFog, "StartFactor") 752 | self.layout.prop(context.object.WowFog, "Color1") 753 | self.layout.prop(context.object.WowFog, "EndDist2") 754 | self.layout.prop(context.object.WowFog, "StartFactor2") 755 | self.layout.prop(context.object.WowFog, "Color2") 756 | 757 | @classmethod 758 | def poll(cls, context): 759 | return (context.object is not None 760 | and context.object.data is not None 761 | and isinstance(context.object.data,bpy.types.Mesh) 762 | and context.object.WowFog.Enabled 763 | ) 764 | 765 | def UpdateFogColor(self, context): 766 | bpy.context.scene.objects.active.color = (self.Color1[0], self.Color1[1], self.Color1[2], 0.5) 767 | 768 | 769 | class WowFogPropertyGroup(bpy.types.PropertyGroup): 770 | 771 | Enabled = bpy.props.BoolProperty( 772 | name="", 773 | description="Enable WoW WMO fog properties" 774 | ) 775 | 776 | FogID = bpy.props.IntProperty( 777 | name="WMO Group ID", 778 | description="Used internally for exporting", 779 | default= 0, 780 | ) 781 | 782 | IgnoreRadius = bpy.props.BoolProperty( 783 | name="Ignore Radius", 784 | description="Ignore radius in CWorldView::QueryCameraFog", 785 | default = False 786 | ) 787 | 788 | Unknown = bpy.props.BoolProperty( 789 | name="Unknown Flag", 790 | description="Check that in if you know what it is", 791 | default = False 792 | ) 793 | 794 | InnerRadius = bpy.props.FloatProperty( 795 | name="Inner Radius (%)", 796 | description="A radius of fog starting to fade", 797 | default=100.0, 798 | min=0.0, 799 | max=100.0 800 | ) 801 | 802 | EndDist = bpy.props.FloatProperty( 803 | name="Farclip", 804 | description="Fog farclip", 805 | default=70.0, 806 | min=0.0, 807 | max=2048.0 808 | ) 809 | 810 | StartFactor = bpy.props.FloatProperty( 811 | name="Nearclip", 812 | description="Fog nearclip", 813 | default=0.1, 814 | min=0.0, 815 | max=1.0 816 | ) 817 | 818 | Color1 = bpy.props.FloatVectorProperty( 819 | name="Color", 820 | subtype='COLOR', 821 | default=(1,1,1), 822 | min=0.0, 823 | max=1.0, 824 | update=UpdateFogColor 825 | ) 826 | 827 | EndDist2 = bpy.props.FloatProperty( 828 | name="Underwater farclip", 829 | description="Underwater fog farclip", 830 | default=70.0, 831 | min=0.0, 832 | max=250.0 833 | ) 834 | 835 | StartFactor2 = bpy.props.FloatProperty( 836 | name="Underwater nearclip", 837 | description="Underwater fog nearclip", 838 | default=0.1, 839 | min=0.0, 840 | max=1.0 841 | ) 842 | 843 | Color2 = bpy.props.FloatVectorProperty( 844 | name="Underwater Color", 845 | subtype='COLOR', 846 | default=(1,1,1), 847 | min=0.0, 848 | max=1.0 849 | ) 850 | 851 | def RegisterWowFogProperties(): 852 | bpy.types.Object.WowFog = bpy.props.PointerProperty(type=WowFogPropertyGroup) 853 | 854 | def UnregisterWowFogProperties(): 855 | bpy.types.Object.WowFog = None 856 | 857 | 858 | ############################### 859 | ## WMO Toolbar 860 | ############################### 861 | 862 | def update_wow_visibility(self, context): 863 | values = self.WoWVisibility 864 | for obj in self.objects: 865 | if obj.type == "MESH": 866 | if obj.WowWMOGroup.Enabled: 867 | if obj.WowWMOGroup.PlaceType == '8': 868 | obj.hide = False if '0' in values else True 869 | else: 870 | obj.hide = False if '1' in values else True 871 | elif obj.WowPortalPlane.Enabled: 872 | obj.hide = False if '2' in values else True 873 | elif obj.WowFog.Enabled: 874 | obj.hide = False if '3' in values else True 875 | elif obj.WowLiquid.Enabled: 876 | obj.hide = False if '4' in values else True 877 | elif obj.type == "LAMP" and obj.data.WowLight.Enabled: 878 | obj.hide = False if '5' in values else True 879 | 880 | 881 | def update_liquid_flags(self, context): 882 | value = self.WoWLiquidFlags 883 | 884 | water = bpy.context.scene.objects.active 885 | mesh = water.data 886 | if water.WowLiquid.Enabled: 887 | layer = mesh.vertex_colors.get("flag_" + value) 888 | 889 | if layer: 890 | layer.active = True 891 | mesh.use_paint_mask = True 892 | else: 893 | layer = mesh.vertex_colors.new("flag_" + value) 894 | layer.active = True 895 | 896 | 897 | def get_doodad_sets(self, context): 898 | has_global = False 899 | doodad_set_objects = set() 900 | doodad_sets = [] 901 | 902 | for obj in bpy.context.scene.objects: 903 | if obj.WoWDoodad.Enabled and obj.parent: 904 | if obj.parent.name != "Set_$DefaultGlobal": 905 | doodad_set_objects.add(obj.parent) 906 | else: 907 | has_global = True 908 | 909 | for index, obj in enumerate(sorted(doodad_set_objects, key=lambda x:x.name), 1 + has_global): 910 | doodad_sets.append((obj.name, obj.name, "", 'SCENE_DATA', index)) 911 | 912 | doodad_sets.insert(0, ("None", "No set", "", 'X', 0)) 913 | if has_global: 914 | doodad_sets.insert(1, ("Set_$DefaultGlobal", "Set_$DefaultGlobal", "", 'WORLD', 1)) 915 | 916 | return doodad_sets 917 | 918 | 919 | def switch_doodad_set(self, context): 920 | set = self.WoWDoodadVisibility 921 | 922 | for obj in bpy.context.scene.objects: 923 | if obj.WoWDoodad.Enabled: 924 | if obj.parent: 925 | name = obj.parent.name 926 | obj.hide = set == "None" or name != set and name != "Set_$DefaultGlobal" 927 | else: 928 | obj.hide = True 929 | 930 | 931 | def RegisterWoWVisibilityProperties(): 932 | bpy.types.Scene.WoWVisibility = bpy.props.EnumProperty( 933 | items=[ 934 | ('0', "Outdoor", "Display outdoor groups", 'BBOX', 0x1), 935 | ('1', "Indoor", "Display indoor groups", 'ROTATE', 0x2), 936 | ('2', "Portals", "Display portals", 'MOD_PARTICLES', 0x4), 937 | ('3', "Fogs", "Display fogs", 'FORCE_TURBULENCE', 0x8), 938 | ('4', "Liquids", "Display liquids", 'MOD_FLUIDSIM', 0x10), 939 | ('5', "Lights", "Display lights", 'LAMP_SPOT', 0x20)], 940 | options={'ENUM_FLAG'}, 941 | default={'0', '1', '2', '3', '4', '5'}, 942 | update=update_wow_visibility 943 | ) 944 | 945 | bpy.types.Scene.WoWLiquidFlags = bpy.props.EnumProperty( 946 | items=[ 947 | ('0x1', "Flag 0x01", "Switch to this flag", 'MOD_SOFT', 0), 948 | ('0x2', "Flag 0x02", "Switch to this flag", 'MOD_SOFT', 1), 949 | ('0x4', "Flag 0x04", "Switch to this flag", 'MOD_SOFT', 2), 950 | ('0x8', "Invisible", "Switch to this flag", 'RESTRICT_VIEW_OFF', 3), 951 | ('0x10', "Flag 0x10", "Switch to this flag", 'MOD_SOFT', 4), 952 | ('0x20', "Flag 0x20", "Switch to this flag", 'MOD_SOFT', 5), 953 | ('0x40', "Flag 0x40", "Switch to this flag", 'MOD_SOFT', 6), 954 | ('0x80', "Flag 0x80", "Switch to this flag", 'MOD_SOFT', 7)], 955 | default='0x1', 956 | update=update_liquid_flags 957 | ) 958 | 959 | bpy.types.Scene.WoWDoodadVisibility = bpy.props.EnumProperty( 960 | name="", 961 | description="Switch doodad sets", 962 | items=get_doodad_sets, 963 | update=switch_doodad_set 964 | ) 965 | 966 | def UnregisterWoWVisibilityProperties(): 967 | bpy.types.Scene.WoWVisibility = None 968 | bpy.types.Scene.WoWLiquidFlags = None 969 | bpy.types.Scene.WoWDoodadVisibility = None 970 | 971 | class WMOToolsPanelObjectMode(bpy.types.Panel): 972 | bl_label = 'Quick WMO' 973 | bl_idname = 'WMOQuickPanelObjMode' 974 | bl_space_type = 'VIEW_3D' 975 | bl_region_type = 'TOOLS' 976 | bl_context = 'objectmode' 977 | bl_category = 'WMO' 978 | 979 | def draw(self, context): 980 | layout = self.layout.split() 981 | 982 | has_sets = True if bpy.context.scene.WoWRoot.MODS_Sets else False 983 | game_data_loaded = hasattr(bpy, "wow_game_data") and bpy.wow_game_data.files 984 | 985 | col = layout.column(align=True) 986 | 987 | col.label(text="Display:") 988 | col_row = col.row() 989 | col_row.column(align=True).prop(context.scene, "WoWVisibility") 990 | col_col = col_row.column(align=True) 991 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'Outdoor' 992 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'Indoor' 993 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'WowPortalPlane' 994 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'WowFog' 995 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'WowLiquid' 996 | col_col.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'WowLight' 997 | 998 | if not bpy.context.scene.WoWRoot.MODS_Sets: 999 | box2_row2 = col.row() 1000 | box2_row2.prop(context.scene, "WoWDoodadVisibility", expand=False) 1001 | box2_row2.operator("scene.wow_wmo_select_entity", text='', icon='VIEWZOOM').Entity = 'WoWDoodad' 1002 | 1003 | col.separator() 1004 | col.label(text="Add to scene:") 1005 | box1 = col.box().column(align=True) 1006 | box1_col = box1.column(align=True) 1007 | box1_row1 = box1_col.row(align=True) 1008 | box1_row1.operator("scene.wow_add_fog", text = 'Fog', icon = 'GROUP_VERTEX') 1009 | box1_row1.operator("scene.wow_add_water", text = 'Water', icon = 'MOD_WAVE') 1010 | box1_row2 = box1_col.row(align=True) 1011 | if game_data_loaded: 1012 | if not has_sets: 1013 | box1_row2.operator("scene.wow_wmo_import_doodad_from_wmv", text='M2', icon = 'LOAD_FACTORY') 1014 | box1_row2.operator("scene.wow_import_last_wmo_from_wmv", text = 'WMO', icon = 'APPEND_BLEND') 1015 | 1016 | box1_col.operator("scene.wow_add_scale_reference", text = 'Scale', icon = 'OUTLINER_OB_ARMATURE') 1017 | 1018 | col.label(text="Game data:") 1019 | icon = 'COLOR_GREEN' if game_data_loaded else 'COLOR_RED' 1020 | text = "Unload game data" if game_data_loaded else "Load game data" 1021 | col.operator("scene.load_wow_filesystem", text=text, icon = icon) 1022 | 1023 | if bpy.context.selected_objects: 1024 | col.separator() 1025 | col.label(text="Selected:") 1026 | box = col.box().column(align=True) 1027 | #box.label(text="Convert:") 1028 | box.menu("view3D.convert_to_menu", text="Convert selected") 1029 | box.label(text="Apply:") 1030 | box_col = box.column(align=True) 1031 | box_col.operator("scene.wow_quick_collision", text='Quick collision', icon='STYLUS_PRESSURE') 1032 | box_col.operator("scene.wow_fill_textures", text='Fill texture paths', icon='FILE_IMAGE') 1033 | box_col.operator("scene.wow_set_portal_dir_alg", text='Set portal dir.', icon='FILE_REFRESH') 1034 | box_col.operator("scene.wow_bake_portal_relations", text='Bake portal rels.', icon='LINKED') 1035 | box.label(text="Doodads:") 1036 | box_col2 = box.column(align=True) 1037 | if not has_sets: 1038 | box_col2.operator("scene.wow_doodad_set_add", text='Add to doodadset', icon='ZOOMIN') 1039 | box_col2.operator("scene.wow_doodads_bake_color", text='Bake color', icon='GROUP_VCOL') 1040 | box_col2.operator("scene.wow_doodad_set_color", text='Set color', icon='COLOR') 1041 | box_col2.operator("scene.wow_doodad_set_template_action", text='Template action', icon='FORCE_MAGNETIC') 1042 | else: 1043 | box_col2.operator("scene.wow_clear_preserved_doodad_sets", text='Clear doodad sets', icon='CANCEL') 1044 | 1045 | class ConvertOperators(bpy.types.Menu): 1046 | bl_label = "Convert" 1047 | bl_idname = "view3D.convert_to_menu" 1048 | bl_options = {'REGISTER'} 1049 | 1050 | def draw(self, context): 1051 | layout = self.layout 1052 | col = layout.column() 1053 | col.operator("scene.wow_selected_objects_to_group", text='To WMO group', icon='OBJECT_DATA') 1054 | col.operator("scene.wow_selected_objects_to_wow_material", text='To WMO material', icon='SMOOTH') 1055 | col.operator("scene.wow_selected_objects_to_portals", text='To WMO portal', icon='MOD_MIRROR') 1056 | col.operator("scene.wow_texface_to_material", text='Texface to material', icon='TEXTURE_DATA') 1057 | 1058 | class INFO_MT_mesh_WoW_components_add(bpy.types.Menu): 1059 | bl_label = "WoW" 1060 | bl_idname = "view3D.add_wow_components_menu" 1061 | bl_options = {'REGISTER'} 1062 | 1063 | def draw(self, context): 1064 | layout = self.layout 1065 | col = layout.column() 1066 | col.operator("scene.wow_add_fog", text = 'Fog', icon = 'GROUP_VERTEX') 1067 | col.operator("scene.wow_add_water", text = 'Water', icon = 'MOD_WAVE') 1068 | col.operator("scene.wow_add_scale_reference", text = 'Scale', icon = 'OUTLINER_OB_ARMATURE') 1069 | 1070 | if hasattr(bpy, "wow_game_data") and bpy.wow_game_data.files: 1071 | col.operator("scene.wow_wmo_import_doodad_from_wmv", text='M2', icon='LOAD_FACTORY') 1072 | col.operator("scene.wow_import_last_wmo_from_wmv", text='WMO', icon='APPEND_BLEND') 1073 | 1074 | def wow_components_add_menu_item(self, context): 1075 | self.layout.menu("view3D.add_wow_components_menu", icon = 'SOLO_ON') 1076 | 1077 | 1078 | class WoWToolsPanelLiquidFlags(bpy.types.Panel): 1079 | bl_label = 'Liquid Flags' 1080 | bl_idname = 'WMOQuickPanelVertexColorMode' 1081 | bl_space_type = 'VIEW_3D' 1082 | bl_region_type = 'TOOLS' 1083 | bl_context = 'vertexpaint' 1084 | bl_category = 'WMO' 1085 | 1086 | def draw(self, context): 1087 | 1088 | layout = self.layout.split() 1089 | 1090 | col = layout.column() 1091 | 1092 | col.label(text="Flags") 1093 | col.prop(context.scene, "WoWLiquidFlags", expand=True) 1094 | 1095 | col.label(text="Actions") 1096 | col.operator("scene.wow_mliq_change_flags", text = 'Add flag', icon = 'MOD_SOFT').Action = "ADD" 1097 | col.operator("scene.wow_mliq_change_flags", text = 'Fill all', icon = 'OUTLINER_OB_LATTICE').Action = "ADD_ALL" 1098 | col.operator("scene.wow_mliq_change_flags", text = 'Clear flag', icon = 'LATTICE_DATA').Action = "CLEAR" 1099 | col.operator("scene.wow_mliq_change_flags", text = 'Clear all', icon = 'MOD_LATTICE').Action = "CLEAR_ALL" 1100 | 1101 | @classmethod 1102 | def poll(cls, context): 1103 | return (context.object is not None 1104 | and context.object.data is not None 1105 | and isinstance(context.object.data,bpy.types.Mesh) 1106 | and context.object.WowLiquid.Enabled 1107 | ) 1108 | 1109 | def register(): 1110 | RegisterWowRootProperties() 1111 | RegisterWoWDoodadProperties() 1112 | RegisterWowMaterialProperties() 1113 | RegisterWowLiquidProperties() 1114 | RegisterWowLightProperties() 1115 | RegisterWowVertexInfoProperties() 1116 | RegisterWowWMOGroupProperties() 1117 | RegisterWowPortalPlaneProperties() 1118 | RegisterWoWVisibilityProperties() 1119 | RegisterWowFogProperties() 1120 | bpy.types.INFO_MT_add.prepend(wow_components_add_menu_item) 1121 | 1122 | def unregister(): 1123 | UnregisterWowRootProperties() 1124 | UnregisterWoWDoodadProperties() 1125 | UnregisterWowMaterialProperties() 1126 | UnregisterWowLiquidProperties() 1127 | UnregisterWowLightProperties() 1128 | UnregisterWowVertexInfoProperties() 1129 | UnregisterWowWMOGroupProperties() 1130 | UnregisterWowPortalPlaneProperties() 1131 | UnregisterWoWVisibilityProperties() 1132 | UnregisterWowFogProperties() 1133 | bpy.types.INFO_MT_add.remove(wow_components_add_menu_item) 1134 | 1135 | 1136 | 1137 | --------------------------------------------------------------------------------