├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py └── addon ├── __init__.py ├── icons ├── __init__.py ├── hlmv.png ├── mdl.png ├── missing.png ├── qc.png ├── smd.png └── vmf.png ├── ops ├── __init__.py ├── backup.py ├── compile_qc.py ├── export_auto.py ├── export_meshes.py ├── export_vmf.py ├── generate_qc.py ├── list_operator.py ├── open_folder.py ├── pose_bone_transforms.py ├── rig_simulation.py ├── triangulate.py ├── view_model.py └── weighted_normal.py ├── props ├── __init__.py ├── addon_prefs.py ├── attachment_props.py ├── event_props.py ├── game_props.py ├── global_props.py ├── map_props.py ├── material_folder_props.py ├── model_props.py ├── particle_props.py ├── sequence_props.py ├── skin_props.py └── surface_props.py ├── types ├── __init__.py ├── map_export │ ├── __init__.py │ ├── brush.py │ ├── displacement.py │ └── vmf.py ├── model_export │ ├── __init__.py │ ├── fbx.py │ ├── model.py │ └── smd.py └── pyvmf │ ├── __init__.py │ ├── importer.py │ ├── pyvmf.py │ └── tools.py ├── ui ├── __init__.py ├── lists.py └── panels.py └── utils ├── __init__.py ├── backup.py ├── common.py └── game.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Environments 101 | .env 102 | .venv 103 | env/ 104 | venv/ 105 | ENV/ 106 | env.bak/ 107 | venv.bak/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyproject 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | .dmypy.json 122 | dmypy.json 123 | 124 | # Pyre type checker 125 | .pyre/ 126 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SourceOps 2 | SourceOps is a Blender addon for exporting models to Source 1. \ 3 | *Requires Blender 2.83 or newer.* 4 | 5 | ## Table of Contents 6 | 1. [Features](#features) 7 | 2. [Installation](#installation) 8 | 3. [Usage](#usage) 9 | 4. [Links](#links) 10 | 4. [Credits](#credits) 11 | 5. [Support Me](#support-me) 12 | 13 | ## Features 14 | - Export objects as SMD or FBX 15 | - Export actions as SMD 16 | - Generate a QC based on UI settings 17 | - Buttons to compile and view models 18 | - Experimental export for brushes and displacements to VMF 19 | - Automatically rig rigid body simulations 20 | - Add Triangulate / Weighted Normal modifiers 21 | - Copy pose bone location / rotation to clipboard 22 | - Works on Linux with Wine 23 | 24 | ## Installation 25 | 1. Get Blender 2.83 or newer from [blender.org](https://www.blender.org/download) or [Steam](https://store.steampowered.com/app/365670/Blender). 26 | 2. Download the [latest SourceOps release](https://github.com/bonjorno7/SourceOps/releases), **don't** unzip. 27 | 3. Open Blender and do these steps: 28 | 1. Go to `Edit > Preferences`. 29 | 2. Go to the `Add-ons` tab. 30 | 3. Click `Install...` in the top-right of the window. 31 | 4. Browse to the SourceOps zip file and select it, then click `Install Add-on`. 32 | 5. SourceOps should be the only add-on shown if installed correctly. 33 | 6. Check the box on the left and wait a moment for activation to complete. 34 | 7. If you're on Linux, set the path for [Wine](https://www.winehq.org) in the SourceOps preferences. 35 | 36 | ## Usage 37 | - [Old SourceOps tutorial on YouTube](https://www.youtube.com/watch?v=kRCIWQZywMs) 38 | 39 | ## Links 40 | - [SourceOps on Valve Developer Wiki](https://developer.valvesoftware.com/wiki/SourceOps) 41 | - [SourceOps / SourceIO on Discord](https://discord.gg/N35zhHm) 42 | 43 | ## Credits 44 | - [bonjorno7](https://github.com/bonjorno7/SourceOps) 45 | - [CabbageMcGravel](https://github.com/CabbageMcGravel) 46 | - [GorangeNinja](https://github.com/GorangeNinja) 47 | - [JonasAlmaas](https://github.com/JonasAlmaas) 48 | - [KrystianoXPL](https://github.com/KrystianoXPL) 49 | - [Peak-CDE](https://github.com/Peak-CDE) 50 | - [REDxEYE](https://github.com/REDxEYE) 51 | - [SethTooQuick](https://github.com/SethTooQuick) 52 | - [VortexParadox](https://github.com/VortexParadox) 53 | - [xchellx](https://github.com/xchellx) 54 | - [Horiuchi](https://github.com/horiuchii) 55 | 56 | ## Support Me 57 | - Buy my other addons on [Gumroad](https://bonjorno7.gumroad.com) or [Blender Market](https://blendermarket.com/creators/bonjorno7). 58 | - Donate to me on [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=43R2CKWLJZ78S). 59 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | bl_info = { 2 | 'name': 'SourceOps', 3 | 'author': 'bonjorno7, Almaas, Cabbage McGravel, CryptAlchemy, Gorange, Krystian, RED_EYE, SethTooQuick, Yonder', 4 | 'description': 'A more convenient alternative to Blender Source Tools', 5 | 'blender': (2, 83, 0), 6 | 'version': (0, 7, 5), 7 | 'location': '3D View > Sidebar', 8 | 'category': 'Import-Export', 9 | } 10 | 11 | 12 | from . import addon 13 | 14 | 15 | def register(): 16 | addon.register() 17 | 18 | 19 | def unregister(): 20 | addon.unregister() 21 | -------------------------------------------------------------------------------- /addon/__init__.py: -------------------------------------------------------------------------------- 1 | from . import utils 2 | from . import props 3 | from . import icons 4 | from . import ops 5 | from . import ui 6 | 7 | 8 | def register(): 9 | props.register() 10 | icons.register() 11 | ops.register() 12 | ui.register() 13 | 14 | 15 | def unregister(): 16 | ui.unregister() 17 | ops.unregister() 18 | props.unregister() 19 | icons.unregister() 20 | -------------------------------------------------------------------------------- /addon/icons/__init__.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bpy.utils.previews 3 | import os 4 | 5 | 6 | pcoll = None 7 | 8 | 9 | def id(identifier): 10 | global pcoll 11 | 12 | try: 13 | return pcoll[identifier.lower()].icon_id 14 | 15 | except: 16 | return pcoll['missing'].icon_id 17 | 18 | 19 | def register(): 20 | global pcoll 21 | pcoll = bpy.utils.previews.new() 22 | directory = os.path.dirname(__file__) 23 | 24 | for filename in os.listdir(directory): 25 | if filename.lower().endswith('.png'): 26 | name = filename.lower()[0:-4] 27 | path = os.path.join(directory, filename) 28 | pcoll.load(name, path, 'IMAGE') 29 | 30 | 31 | def unregister(): 32 | global pcoll 33 | bpy.utils.previews.remove(pcoll) 34 | -------------------------------------------------------------------------------- /addon/icons/hlmv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/hlmv.png -------------------------------------------------------------------------------- /addon/icons/mdl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/mdl.png -------------------------------------------------------------------------------- /addon/icons/missing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/missing.png -------------------------------------------------------------------------------- /addon/icons/qc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/qc.png -------------------------------------------------------------------------------- /addon/icons/smd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/smd.png -------------------------------------------------------------------------------- /addon/icons/vmf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bonjorno7/SourceOps/b5e57e4f15d6ee2810693684bfebca83bbbe7b2b/addon/icons/vmf.png -------------------------------------------------------------------------------- /addon/ops/__init__.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . import open_folder 3 | from . import export_meshes 4 | from . import generate_qc 5 | from . import compile_qc 6 | from . import view_model 7 | from . import export_auto 8 | from . import list_operator 9 | from . import export_vmf 10 | from . import rig_simulation 11 | from . import pose_bone_transforms 12 | from . import weighted_normal 13 | from . import triangulate 14 | from . import backup 15 | 16 | classes = ( 17 | open_folder.SOURCEOPS_OT_OpenFolder, 18 | export_meshes.SOURCEOPS_OT_ExportMeshes, 19 | generate_qc.SOURCEOPS_OT_GenerateQC, 20 | compile_qc.SOURCEOPS_OT_CompileQC, 21 | view_model.SOURCEOPS_OT_ViewModel, 22 | export_auto.SOURCEOPS_OT_ExportAuto, 23 | list_operator.SOURCEOPS_OT_ListOperator, 24 | export_vmf.SOURCEOPS_OT_ExportVMF, 25 | rig_simulation.SOURCEOPS_OT_RigSimulation, 26 | pose_bone_transforms.SOURCEOPS_OT_PoseBoneTransforms, 27 | weighted_normal.SOURCEOPS_OT_weighted_normal, 28 | triangulate.SOURCEOPS_OT_triangulate, 29 | backup.SOURCEOPS_OT_BackupPreferences, 30 | backup.SOURCEOPS_OT_RestorePreferences, 31 | ) 32 | 33 | 34 | def register(): 35 | for cls in classes: 36 | bpy.utils.register_class(cls) 37 | 38 | bpy.types.VIEW3D_MT_pose_context_menu.append(pose_bone_transforms.menu_func) 39 | 40 | def unregister(): 41 | bpy.types.VIEW3D_MT_pose_context_menu.remove(pose_bone_transforms.menu_func) 42 | 43 | for cls in reversed(classes): 44 | bpy.utils.unregister_class(cls) 45 | -------------------------------------------------------------------------------- /addon/ops/backup.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bpy_extras 3 | from .. import utils 4 | 5 | 6 | class SOURCEOPS_OT_BackupPreferences(bpy.types.Operator, bpy_extras.io_utils.ExportHelper): 7 | bl_idname = 'sourceops.backup_preferences' 8 | bl_label = 'Backup Preferences' 9 | bl_options = {'REGISTER', 'INTERNAL'} 10 | bl_description = '.\n'.join(( 11 | 'Save addon preferences to a file', 12 | 'Made possible by PowerBackup')) 13 | 14 | filter_glob: bpy.props.StringProperty(default='*.json', options={'HIDDEN'}) 15 | filename_ext: bpy.props.StringProperty(default='.json', options={'HIDDEN'}) 16 | 17 | def invoke(self, context, event): 18 | self.filepath = utils.backup.filepath() 19 | return super().invoke(context, event) 20 | 21 | def execute(self, context): 22 | result = utils.backup.backup(self.filepath) 23 | self.report(result[0], result[1]) 24 | return result[2] 25 | 26 | 27 | class SOURCEOPS_OT_RestorePreferences(bpy.types.Operator, bpy_extras.io_utils.ImportHelper): 28 | bl_idname = 'sourceops.restore_preferences' 29 | bl_label = 'Restore Preferences' 30 | bl_options = {'REGISTER', 'UNDO', 'INTERNAL'} 31 | bl_description = '.\n'.join(( 32 | 'Load addon preferences from a file', 33 | 'Made possible by PowerBackup')) 34 | 35 | filter_glob: bpy.props.StringProperty(default='*.json', options={'HIDDEN'}) 36 | filename_ext: bpy.props.StringProperty(default='.json', options={'HIDDEN'}) 37 | 38 | def invoke(self, context, event): 39 | self.filepath = utils.backup.filepath() 40 | return super().invoke(context, event) 41 | 42 | def execute(self, context): 43 | result = utils.backup.restore(self.filepath) 44 | self.report(result[0], result[1]) 45 | return result[2] 46 | -------------------------------------------------------------------------------- /addon/ops/compile_qc.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | from .. types . model_export . model import Model 4 | 5 | 6 | class SOURCEOPS_OT_CompileQC(bpy.types.Operator): 7 | bl_idname = 'sourceops.compile_qc' 8 | bl_options = {'REGISTER'} 9 | bl_label = 'Compile QC' 10 | bl_description = 'Compile this model\'s QC file' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | prefs = utils.common.get_prefs(context) 15 | game = utils.common.get_game(prefs) 16 | sourceops = utils.common.get_globals(context) 17 | model = utils.common.get_model(sourceops) 18 | return prefs and game and sourceops and model 19 | 20 | def invoke(self, context, event): 21 | prefs = utils.common.get_prefs(context) 22 | game = utils.common.get_game(prefs) 23 | sourceops = utils.common.get_globals(context) 24 | model = utils.common.get_model(sourceops) 25 | 26 | if not utils.game.verify(game): 27 | self.report({'ERROR'}, 'Game is invalid') 28 | return {'CANCELLED'} 29 | 30 | source_model = Model(game, model) 31 | error = source_model.compile_qc() 32 | 33 | if error: 34 | self.report({'ERROR'}, error) 35 | return {'CANCELLED'} 36 | 37 | self.report({'INFO'}, 'Compiled QC') 38 | return {'FINISHED'} 39 | -------------------------------------------------------------------------------- /addon/ops/export_auto.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import time 3 | from threading import Lock, Thread 4 | from .. import utils 5 | from .. types . model_export . model import Model 6 | 7 | 8 | class SOURCEOPS_OT_ExportAuto(bpy.types.Operator): 9 | bl_idname = 'sourceops.export_auto' 10 | bl_options = {'REGISTER'} 11 | bl_label = 'Export Auto' 12 | bl_description = 'Export meshes, generate QC, compile QC, view model.\nShift click to export all models.\nCtrl click to customize export steps' 13 | 14 | ctrl: bpy.props.BoolProperty(name='Ctrl', description='Whether Ctrl was held during invoke', options={'HIDDEN', 'SKIP_SAVE'}) 15 | shift: bpy.props.BoolProperty(name='Shift', description='Whether Shift was held during invoke', options={'HIDDEN', 'SKIP_SAVE'}) 16 | 17 | all_models: bpy.props.BoolProperty(name='All Models', description='Export all models in the scene', default=False) 18 | export_meshes: bpy.props.BoolProperty(name='Export Meshes', description='Export the meshes and animations as SMD/FBX', default=True) 19 | generate_qc: bpy.props.BoolProperty(name='Generate QC', description='Generate the QC based on your settings', default=True) 20 | compile_qc: bpy.props.BoolProperty(name='Compile QC', description='Compile the QC to an MDL', default=True) 21 | view_model: bpy.props.BoolProperty(name='View Model', description='Open the selected model in HLMV', default=False) 22 | 23 | def draw(self, context): 24 | layout = self.layout 25 | col = layout.column() 26 | col.prop(self, 'all_models') 27 | 28 | col.prop(self, 'export_meshes') 29 | col.prop(self, 'generate_qc') 30 | col.prop(self, 'compile_qc') 31 | 32 | row = col.row() 33 | row.enabled = not self.all_models 34 | row.prop(self, 'view_model') 35 | 36 | @classmethod 37 | def poll(cls, context): 38 | prefs = utils.common.get_prefs(context) 39 | game = utils.common.get_game(prefs) 40 | sourceops = utils.common.get_globals(context) 41 | model = utils.common.get_model(sourceops) 42 | return prefs and game and sourceops and model 43 | 44 | def invoke(self, context, event): 45 | prefs = utils.common.get_prefs(context) 46 | game = utils.common.get_game(prefs) 47 | 48 | if not utils.game.verify(game): 49 | self.report({'ERROR'}, 'Game is invalid') 50 | return {'CANCELLED'} 51 | 52 | self.ctrl = event.ctrl 53 | self.shift = event.shift 54 | 55 | if self.ctrl: 56 | return context.window_manager.invoke_props_dialog(self) 57 | else: 58 | return self.execute(context) 59 | 60 | def execute(self, context): 61 | prefs = utils.common.get_prefs(context) 62 | game = utils.common.get_game(prefs) 63 | sourceops = utils.common.get_globals(context) 64 | 65 | start = time.time() 66 | 67 | self._lock = Lock() 68 | self._results = [] 69 | 70 | if (not self.ctrl and self.shift) or (self.ctrl and self.all_models): 71 | source_models = [Model(game, model) for model in sourceops.model_items] 72 | 73 | for source_model in source_models: 74 | error = self.export(source_model) 75 | if error: 76 | self.report({'ERROR'}, error) 77 | return {'CANCELLED'} 78 | 79 | threads = [Thread(target=self.compile, args=[m], daemon=True) for m in source_models] 80 | 81 | for thread in threads: 82 | thread.start() 83 | 84 | for thread in threads: 85 | thread.join() 86 | 87 | for error in self._results: 88 | self.report({'ERROR'}, error) 89 | 90 | if self._results: 91 | return {'CANCELLED'} 92 | 93 | self.report({'INFO'}, f'Exported all models in the scene in {round(time.time() - start, 1)} seconds') 94 | return {'FINISHED'} 95 | 96 | else: 97 | model = utils.common.get_model(sourceops) 98 | source_model = Model(game, model) 99 | 100 | error = self.export(source_model) 101 | if error: 102 | self.report({'ERROR'}, error) 103 | return {'CANCELLED'} 104 | 105 | error = self.compile(source_model) 106 | if error: 107 | self.report({'ERROR'}, error) 108 | return {'CANCELLED'} 109 | 110 | forced_static = not model.armature and not model.static 111 | static_message = ' (forced static due to lack of armature)' if forced_static else '' 112 | 113 | self.report({'INFO'}, f'Exported {model.name} in {round(time.time() - start, 1)} seconds{static_message}') 114 | return {'FINISHED'} 115 | 116 | def export(self, source_model: Model): 117 | if not self.ctrl or self.export_meshes: 118 | error = source_model.export_meshes() 119 | if error: 120 | return error 121 | 122 | if not self.ctrl or self.generate_qc: 123 | error = source_model.generate_qc() 124 | if error: 125 | return error 126 | 127 | def compile(self, source_model: Model): 128 | if not self.ctrl or self.compile_qc: 129 | error = source_model.compile_qc() 130 | if error: 131 | with self._lock: 132 | self._results.append(error) 133 | return 134 | 135 | if self.ctrl and (not self.all_models and self.view_model): 136 | error = source_model.view_model() 137 | if error: 138 | with self._lock: 139 | self._results.append(error) 140 | return 141 | -------------------------------------------------------------------------------- /addon/ops/export_meshes.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | from .. types . model_export . model import Model 4 | 5 | 6 | class SOURCEOPS_OT_ExportMeshes(bpy.types.Operator): 7 | bl_idname = 'sourceops.export_meshes' 8 | bl_options = {'REGISTER'} 9 | bl_label = 'Export Meshes' 10 | bl_description = 'Export this model\'s meshes' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | prefs = utils.common.get_prefs(context) 15 | game = utils.common.get_game(prefs) 16 | sourceops = utils.common.get_globals(context) 17 | model = utils.common.get_model(sourceops) 18 | return prefs and game and sourceops and model 19 | 20 | def invoke(self, context, event): 21 | prefs = utils.common.get_prefs(context) 22 | game = utils.common.get_game(prefs) 23 | sourceops = utils.common.get_globals(context) 24 | model = utils.common.get_model(sourceops) 25 | 26 | if not utils.game.verify(game): 27 | self.report({'ERROR'}, 'Game is invalid') 28 | return {'CANCELLED'} 29 | 30 | source_model = Model(game, model) 31 | error = source_model.export_meshes() 32 | 33 | if error: 34 | self.report({'ERROR'}, error) 35 | return {'CANCELLED'} 36 | 37 | self.report({'INFO'}, 'Exported meshes') 38 | return {'FINISHED'} 39 | -------------------------------------------------------------------------------- /addon/ops/export_vmf.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from pathlib import Path 3 | from .. import utils 4 | from .. types . map_export . vmf import VMF, Settings 5 | 6 | 7 | class SOURCEOPS_OT_ExportVMF(bpy.types.Operator): 8 | bl_idname = 'sourceops.export_vmf' 9 | bl_options = {'REGISTER'} 10 | bl_label = 'Export VMF' 11 | bl_description = 'Turn meshes into brushes or displacements and export them to a VMF file' 12 | 13 | @classmethod 14 | def poll(cls, context): 15 | prefs = utils.common.get_prefs(context) 16 | game = utils.common.get_game(prefs) 17 | sourceops = utils.common.get_globals(context) 18 | props = utils.common.get_map(sourceops) 19 | return prefs and game and sourceops and props 20 | 21 | def invoke(self, context, event): 22 | prefs = utils.common.get_prefs(context) 23 | game = utils.common.get_game(prefs) 24 | sourceops = utils.common.get_globals(context) 25 | props = utils.common.get_map(sourceops) 26 | 27 | if not game.mapsrc: 28 | self.report({'INFO'}, 'Please enter a mapsrc folder') 29 | return {'CANCELLED'} 30 | 31 | if not props.name: 32 | self.report({'INFO'}, 'Please enter a map name') 33 | return {'CANCELLED'} 34 | 35 | if not (props.brush_collection or props.disp_collection): 36 | self.report({'INFO'}, 'Please choose a collection') 37 | return {'CANCELLED'} 38 | 39 | mapsrc = bpy.path.abspath(game.mapsrc) 40 | path = str(Path(mapsrc) / props.name) 41 | 42 | if props.brush_collection: 43 | brush_objects = [o for o in props.brush_collection.all_objects if o.type == 'MESH'] 44 | else: 45 | brush_objects = [] 46 | 47 | if props.disp_collection: 48 | disp_objects = [o for o in props.disp_collection.all_objects if o.type == 'MESH'] 49 | else: 50 | disp_objects = [] 51 | 52 | geometry_scale = props.geometry_scale 53 | texture_scale = props.texture_scale 54 | lightmap_scale = props.lightmap_scale 55 | allow_skewed_textures = props.allow_skewed_textures 56 | align_to_grid = props.align_to_grid 57 | 58 | settings = Settings( 59 | brush_objects, 60 | disp_objects, 61 | geometry_scale, 62 | texture_scale, 63 | lightmap_scale, 64 | allow_skewed_textures, 65 | align_to_grid, 66 | ) 67 | vmf = VMF(settings) 68 | vmf.export(path) 69 | 70 | self.report({'INFO'}, 'Exported VMF') 71 | return {'FINISHED'} 72 | -------------------------------------------------------------------------------- /addon/ops/generate_qc.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | from .. types . model_export . model import Model 4 | 5 | 6 | class SOURCEOPS_OT_GenerateQC(bpy.types.Operator): 7 | bl_idname = 'sourceops.generate_qc' 8 | bl_options = {'REGISTER'} 9 | bl_label = 'Generate QC' 10 | bl_description = 'Generate this model\'s QC file' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | prefs = utils.common.get_prefs(context) 15 | game = utils.common.get_game(prefs) 16 | sourceops = utils.common.get_globals(context) 17 | model = utils.common.get_model(sourceops) 18 | return prefs and game and sourceops and model 19 | 20 | def invoke(self, context, event): 21 | prefs = utils.common.get_prefs(context) 22 | game = utils.common.get_game(prefs) 23 | sourceops = utils.common.get_globals(context) 24 | model = utils.common.get_model(sourceops) 25 | 26 | if not utils.game.verify(game): 27 | self.report({'ERROR'}, 'Game is invalid') 28 | return {'CANCELLED'} 29 | 30 | source_model = Model(game, model) 31 | error = source_model.generate_qc() 32 | 33 | if error: 34 | self.report({'ERROR'}, error) 35 | return {'CANCELLED'} 36 | 37 | forced_static = not model.armature and not model.static 38 | static_message = ' (forced static due to lack of armature)' if forced_static else '' 39 | 40 | self.report({'INFO'}, f'Generated QC for {model.name}{static_message}') 41 | return {'FINISHED'} 42 | -------------------------------------------------------------------------------- /addon/ops/list_operator.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. utils import common 3 | 4 | 5 | class SOURCEOPS_OT_ListOperator(bpy.types.Operator): 6 | bl_idname = 'sourceops.list_operator' 7 | bl_options = {'REGISTER', 'UNDO', 'INTERNAL'} 8 | bl_label = 'List Operator' 9 | 10 | @classmethod 11 | def description(cls, context, properties): 12 | action = properties.mode.split('_') 13 | item = properties.item.replace('_', ' ') 14 | 15 | text = f'{action[0]} {item[:-1]}' 16 | if len(action) > 1: 17 | text = f'{text} {action[1]}' 18 | 19 | return text.capitalize() 20 | 21 | mode: bpy.props.EnumProperty( 22 | name='Mode', 23 | description='What to do to the item', 24 | items=[ 25 | ('ADD', 'Add', 'Add an item'), 26 | ('REMOVE', 'Remove', 'Remove an item'), 27 | ('COPY', 'Copy', 'Copy an item'), 28 | ('MOVE_UP', 'Move Up', 'Move an item up'), 29 | ('MOVE_DOWN', 'Move Down', 'Move an item down'), 30 | ], 31 | ) 32 | 33 | item: bpy.props.EnumProperty( 34 | name='Type', 35 | description='Which list to deal with', 36 | items=[ 37 | ('GAMES', 'Games', 'Operate on games'), 38 | ('MODELS', 'Models', 'Operate on models'), 39 | ('MATERIAL_FOLDERS', 'Material Folders', 'Operate on material folders'), 40 | ('SKINS', 'Skins', 'Operate on skins'), 41 | ('SEQUENCES', 'Sequences', 'Operate on sequences'), 42 | ('EVENTS', 'Events', 'Operate on events'), 43 | ('ATTACHMENTS', 'Attachments', 'Operate on attachments'), 44 | ('PARTICLES', 'Particles', 'Operate on particles'), 45 | ('MAPS', 'Maps', 'Operate on maps'), 46 | ], 47 | ) 48 | 49 | def add(self, parent, items, index): 50 | items.add() 51 | index = len(items) - 1 52 | return index 53 | 54 | def remove(self, parent, items, index): 55 | items.remove(index) 56 | index = min( 57 | max(0, index - 1), 58 | max(0, len(items) - 1), 59 | ) 60 | return index 61 | 62 | def copy(self, parent, items, index): 63 | items.add() 64 | old, new = items[index], items[-1] 65 | for key, value in old.items(): 66 | new[key] = value 67 | index = len(items) - 1 68 | return index 69 | 70 | def move(self, parent, items, index, direction): 71 | neighbor = max(0, index + direction) 72 | items.move(neighbor, index) 73 | length = max(0, len(items) - 1) 74 | index = max(0, min(neighbor, length)) 75 | return index 76 | 77 | def move_up(self, parent, items, index): 78 | return self.move(parent, items, index, -1) 79 | 80 | def move_down(self, parent, items, index): 81 | return self.move(parent, items, index, 1) 82 | 83 | def invoke(self, context, event): 84 | prefs = common.get_prefs(context) 85 | game = common.get_game(prefs) 86 | sourceops = common.get_globals(context) 87 | model = common.get_model(sourceops) 88 | sequence = common.get_sequence(model) 89 | 90 | mode_dict = { 91 | 'ADD': self.add, 92 | 'REMOVE': self.remove, 93 | 'COPY': self.copy, 94 | 'MOVE_UP': self.move_up, 95 | 'MOVE_DOWN': self.move_down, 96 | } 97 | 98 | item_dict = { 99 | 'GAMES': (prefs, 'game_items', 'game_index'), 100 | 'MODELS': (sourceops, 'model_items', 'model_index'), 101 | 'MATERIAL_FOLDERS': (model, 'material_folder_items', 'material_folder_index'), 102 | 'SKINS': (model, 'skin_items', 'skin_index'), 103 | 'SEQUENCES': (model, 'sequence_items', 'sequence_index'), 104 | 'EVENTS': (sequence, 'event_items', 'event_index'), 105 | 'ATTACHMENTS': (model, 'attachment_items', 'attachment_index'), 106 | 'PARTICLES': (model, 'particle_items', 'particle_index'), 107 | 'MAPS': (sourceops, 'map_items', 'map_index'), 108 | } 109 | 110 | function = mode_dict[self.mode] 111 | parent, items_name, index_name = item_dict[self.item] 112 | 113 | if self.mode == 'ADD' and not parent: 114 | return {'CANCELLED'} 115 | 116 | if self.mode != 'ADD' and (not parent or not getattr(parent, items_name)): 117 | return {'CANCELLED'} 118 | 119 | items = getattr(parent, items_name) 120 | index = getattr(parent, index_name) 121 | 122 | index = function(parent, items, index) 123 | setattr(parent, index_name, index) 124 | 125 | return {'FINISHED'} 126 | -------------------------------------------------------------------------------- /addon/ops/open_folder.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | from .. types . model_export . model import Model 4 | 5 | 6 | class SOURCEOPS_OT_OpenFolder(bpy.types.Operator): 7 | bl_idname = 'sourceops.open_folder' 8 | bl_options = {'REGISTER'} 9 | bl_label = 'Open Folder' 10 | bl_description = 'Open this model\'s folder in your OS\'s file browser' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | prefs = utils.common.get_prefs(context) 15 | game = utils.common.get_game(prefs) 16 | sourceops = utils.common.get_globals(context) 17 | model = utils.common.get_model(sourceops) 18 | return prefs and game and sourceops and model 19 | 20 | def invoke(self, context, event): 21 | prefs = utils.common.get_prefs(context) 22 | game = utils.common.get_game(prefs) 23 | sourceops = utils.common.get_globals(context) 24 | model = utils.common.get_model(sourceops) 25 | 26 | if not utils.game.verify(game): 27 | self.report({'ERROR'}, 'Game is invalid') 28 | return {'CANCELLED'} 29 | 30 | source_model = Model(game, model) 31 | error = source_model.open_folder() 32 | 33 | if error: 34 | self.report({'ERROR'}, error) 35 | return {'CANCELLED'} 36 | 37 | self.report({'INFO'}, 'Opened folder') 38 | return {'FINISHED'} 39 | -------------------------------------------------------------------------------- /addon/ops/pose_bone_transforms.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import math 3 | 4 | 5 | class SOURCEOPS_OT_PoseBoneTransforms(bpy.types.Operator): 6 | bl_idname = 'sourceops.pose_bone_transforms' 7 | bl_label = 'Pose Bone Transforms' 8 | bl_description = 'Copy parent space transforms of the active pose bone to clipboard' 9 | bl_options = {'REGISTER', 'INTERNAL'} 10 | 11 | type: bpy.props.EnumProperty( 12 | name='Transform Type', 13 | items=[ 14 | ('TRANSLATION', 'Translation', ''), 15 | ('ROTATION', 'Rotation', ''), 16 | ], 17 | ) 18 | 19 | @classmethod 20 | def poll(cls, context: bpy.types.Context) -> bool: 21 | return context.mode == 'POSE' 22 | 23 | def execute(self, context: bpy.types.Context) -> set: 24 | bone = context.active_pose_bone 25 | 26 | if bone is None: 27 | self.report({'INFO'}, 'No active bone') 28 | return {'CANCELLED'} 29 | 30 | if bone.parent: 31 | parent = bone.parent.matrix.inverted_safe() 32 | matrix = parent @ bone.matrix 33 | else: 34 | matrix = bone.matrix 35 | 36 | if self.type == 'ROTATION': 37 | vector = matrix.to_euler() 38 | vector = [math.degrees(n) for n in vector] 39 | else: 40 | vector = matrix.to_translation().xyz 41 | 42 | string = ' '.join(str(round(n, 6)) for n in vector) 43 | context.window_manager.clipboard = string 44 | 45 | self.report({'INFO'}, f'{self.type.capitalize()}: {string}') 46 | return {'FINISHED'} 47 | 48 | 49 | def menu_func(self, context: bpy.types.Context): 50 | layout = self.layout 51 | layout.separator() 52 | 53 | layout.operator('sourceops.pose_bone_transforms', text='Copy Translation for Source').type = 'TRANSLATION' 54 | layout.operator('sourceops.pose_bone_transforms', text='Copy Rotation for Source').type = 'ROTATION' 55 | -------------------------------------------------------------------------------- /addon/ops/rig_simulation.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import mathutils 3 | from .. import utils 4 | 5 | 6 | class SOURCEOPS_OT_RigSimulation(bpy.types.Operator): 7 | '''Duplicate rigid body objects from a collection and rig the copies, then make the bones follow the rigid bodies''' 8 | bl_options = {'REGISTER', 'UNDO'} 9 | bl_idname = 'sourceops.rig_simulation' 10 | bl_label = 'Rig Simulation' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | 15 | # Make sure input and output collections are set 16 | sourceops = utils.common.get_globals(context) 17 | input_collection = sourceops.simulation_input 18 | output_collection = sourceops.simulation_output 19 | return input_collection and output_collection 20 | 21 | def execute(self, context): 22 | 23 | # Switch to object mode 24 | bpy.ops.object.mode_set(mode='OBJECT') 25 | 26 | # Get input and output collections 27 | sourceops = utils.common.get_globals(context) 28 | input_collection = sourceops.simulation_input 29 | output_collection = sourceops.simulation_output 30 | 31 | # Iterate through output objects 32 | for output_obj in output_collection.all_objects: 33 | if output_obj.type not in {'MESH', 'ARMATURE'}: 34 | continue 35 | 36 | # Store object type and data 37 | obj_type = output_obj.type 38 | obj_data = output_obj.data 39 | 40 | # Remove object 41 | bpy.data.objects.remove(output_obj) 42 | 43 | # Remove data 44 | if obj_type == 'MESH': 45 | bpy.data.meshes.remove(obj_data) 46 | elif obj_type == 'ARMATURE': 47 | bpy.data.armatures.remove(obj_data) 48 | 49 | # Create armature 50 | name = f'{output_collection.name} Armature' 51 | arm_data = bpy.data.armatures.new(name=name) 52 | arm_obj = bpy.data.objects.new(name=name, object_data=arm_data) 53 | output_collection.objects.link(arm_obj) 54 | arm_obj.show_in_front = True 55 | 56 | # Iterate through input objects 57 | for input_obj in input_collection.all_objects: 58 | if input_obj.type != 'MESH': 59 | continue 60 | 61 | # Duplicate to output collection 62 | output_obj = input_obj.copy() 63 | output_obj.data = input_obj.data.copy() 64 | output_obj.name = f'Rigged {input_obj.name}' 65 | output_obj.data.name = output_obj.name 66 | output_obj.animation_data_clear() 67 | output_collection.objects.link(output_obj) 68 | 69 | # Reset transforms 70 | output_obj.location = (0, 0, 0) 71 | output_obj.rotation_euler = (0, 0, 0) 72 | output_obj.scale = (1, 1, 1) 73 | 74 | # Remove rigid body properties 75 | if output_obj.rigid_body: 76 | context.view_layer.objects.active = output_obj 77 | bpy.ops.rigidbody.object_remove() 78 | 79 | # Add vertex group 80 | output_obj.vertex_groups.clear() 81 | group = output_obj.vertex_groups.new(name=output_obj.name) 82 | indices = list(range(len(output_obj.data.vertices))) 83 | group.add(index=indices, weight=1.0, type='REPLACE') 84 | 85 | # Add armature modifier 86 | mod = output_obj.modifiers.new('Armature', 'ARMATURE') 87 | mod.use_vertex_groups = True 88 | mod.object = arm_obj 89 | 90 | # Switch to armature edit mode 91 | context.view_layer.objects.active = arm_obj 92 | bpy.ops.object.mode_set(mode='EDIT') 93 | 94 | # Iterate through output objects 95 | for output_obj in output_collection.all_objects: 96 | if output_obj.type != 'MESH': 97 | continue 98 | 99 | # Add bone 100 | bone = arm_data.edit_bones.new(output_obj.name) 101 | bone.tail.z = output_obj.dimensions[2] 102 | 103 | # Switch to armature pose mode 104 | context.view_layer.objects.active = arm_obj 105 | bpy.ops.object.mode_set(mode='POSE') 106 | 107 | # Iterate through bones 108 | for bone in arm_obj.pose.bones: 109 | 110 | # Add bone constraint 111 | constraint = bone.constraints.new('CHILD_OF') 112 | name = bone.name.replace('Rigged ', '', 1) 113 | constraint.target = bpy.data.objects[name] 114 | constraint.inverse_matrix = mathutils.Matrix.Identity(4) 115 | 116 | # Switch to object mode 117 | bpy.ops.object.mode_set(mode='OBJECT') 118 | 119 | # Report to user and finish 120 | self.report({'INFO'}, f'Rigged Simulation') 121 | return {'FINISHED'} 122 | -------------------------------------------------------------------------------- /addon/ops/triangulate.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_OT_triangulate(bpy.types.Operator): 5 | bl_idname = 'sourceops.triangulate' 6 | bl_label = 'Add Triangulate Modifier' 7 | bl_description = 'Add a triangulate modifier to the selected objects and remove existing triangulate modifiers' 8 | bl_options = {'REGISTER', 'UNDO'} 9 | 10 | quad_method: bpy.props.EnumProperty( 11 | name='Quad Method', 12 | description='Method for splitting the quads into triangles', 13 | items=[ 14 | ('BEAUTY', 'Beauty', 'Split the quads in nice triangles, slower method'), 15 | ('FIXED', 'Fixed', 'Split the quads on the first and third vertices'), 16 | ('FIXED_ALTERNATE', 'Fixed Alternate', 'Split the quads on the 2nd and 4th vertice'), 17 | ('SHORTEST_DIAGONAL', 'Shortest Diagonal', 'Split the quads based on the distance between the vertices'), 18 | ], 19 | default='BEAUTY', 20 | ) 21 | 22 | ngon_method: bpy.props.EnumProperty( 23 | name='N-gon Method', 24 | description='Method for splitting the n-gons into triangles', 25 | items=[ 26 | ('BEAUTY', 'Beauty', 'Arrange the triangles evenly (slow)'), 27 | ('CLIP', 'Clip', 'Split the polygons with an ear clipping algorithm'), 28 | ], 29 | default='BEAUTY', 30 | ) 31 | 32 | min_vertices: bpy.props.IntProperty( 33 | name='Minimum Vertices', 34 | description='Triangulate only polygons with vertex count greater than or equal to this number', 35 | min=4, 36 | default=4, 37 | ) 38 | 39 | keep_custom_normals: bpy.props.BoolProperty( 40 | name='Keep Normals', 41 | description='Try to preserve custom normals.\nWarning: Depending on chosen triangulation method, shading may not be fully preserved, "Fixed" method usually gives the best result here.\nDoes nothing in Blender 4.2 or newer', 42 | default=True, 43 | ) 44 | 45 | @classmethod 46 | def poll(cls, context): 47 | return context.selected_objects 48 | 49 | def execute(self, context): 50 | for obj in context.selected_objects: 51 | if obj.type in {'MESH', 'CURVE', 'SURFACE', 'FONT'}: 52 | for mod in obj.modifiers[:]: 53 | if mod.type == 'TRIANGULATE': 54 | obj.modifiers.remove(mod) 55 | 56 | mod = obj.modifiers.new('Triangulate', 'TRIANGULATE') 57 | mod.quad_method = self.quad_method 58 | mod.ngon_method = self.ngon_method 59 | mod.min_vertices = self.min_vertices 60 | if hasattr(mod, 'keep_custom_normals'): 61 | mod.keep_custom_normals = self.keep_custom_normals 62 | 63 | return {'FINISHED'} 64 | -------------------------------------------------------------------------------- /addon/ops/view_model.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | from .. types . model_export . model import Model 4 | 5 | 6 | class SOURCEOPS_OT_ViewModel(bpy.types.Operator): 7 | bl_idname = 'sourceops.view_model' 8 | bl_options = {'REGISTER'} 9 | bl_label = 'View Model' 10 | bl_description = 'View this model in HLMV' 11 | 12 | @classmethod 13 | def poll(cls, context): 14 | prefs = utils.common.get_prefs(context) 15 | game = utils.common.get_game(prefs) 16 | sourceops = utils.common.get_globals(context) 17 | model = utils.common.get_model(sourceops) 18 | return prefs and game and sourceops and model 19 | 20 | def invoke(self, context, event): 21 | prefs = utils.common.get_prefs(context) 22 | game = utils.common.get_game(prefs) 23 | sourceops = utils.common.get_globals(context) 24 | model = utils.common.get_model(sourceops) 25 | 26 | if not utils.game.verify(game): 27 | self.report({'ERROR'}, 'Game is invalid') 28 | return {'CANCELLED'} 29 | 30 | source_model = Model(game, model) 31 | error = source_model.view_model() 32 | 33 | if error: 34 | self.report({'ERROR'}, error) 35 | return {'CANCELLED'} 36 | 37 | plusplus = '++' if source_model.hlmv.stem.endswith('plusplus') else '' 38 | self.report({'INFO'}, f'Viewing model in HLMV{plusplus}') 39 | return {'FINISHED'} 40 | -------------------------------------------------------------------------------- /addon/ops/weighted_normal.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_OT_weighted_normal(bpy.types.Operator): 5 | bl_idname = 'sourceops.weighted_normal' 6 | bl_label = 'Add Weighted Normal Modifier' 7 | bl_description = 'Add a weighted normal modifier to the selected objects and remove existing weighted normal modifiers' 8 | bl_options = {'REGISTER', 'UNDO'} 9 | 10 | mode: bpy.props.EnumProperty( 11 | name='Weighting Mode', 12 | description='Weighted vertex normal mode to use', 13 | items=[ 14 | ('FACE_AREA', 'Face Area', 'Generate face area weighted normals'), 15 | ('CORNER_ANGLE', 'Corner Angle', 'Generate corner angle weighted normals'), 16 | ('FACE_AREA_WITH_ANGLE', 'Face Area And Angle', 'Generated normals weighted by both face area and angle'), 17 | ], 18 | default='FACE_AREA', 19 | ) 20 | 21 | weight: bpy.props.IntProperty( 22 | name='Weight', 23 | description='Corrective factor applied to faces’ weights, 50 is neutral, lower values increase weight of weak faces, higher values increase weight of strong faces', 24 | min=1, 25 | max=100, 26 | default=50, 27 | ) 28 | 29 | thresh: bpy.props.FloatProperty( 30 | name='Threshold', 31 | description='Threshold value for different weights to be considered equal', 32 | min=0, 33 | max=10, 34 | default=0.01, 35 | ) 36 | 37 | keep_sharp: bpy.props.BoolProperty( 38 | name='Keep Sharp', 39 | description='Keep sharp edges as computed for default split normals, instead of setting a single weighted normal for each vertex', 40 | default=True, 41 | ) 42 | 43 | use_face_influence: bpy.props.BoolProperty( 44 | name='Face Influence', 45 | description='Use influence of face for weighting', 46 | default=False, 47 | ) 48 | 49 | @classmethod 50 | def poll(cls, context): 51 | return context.selected_objects 52 | 53 | def execute(self, context): 54 | bpy.ops.object.shade_smooth() 55 | 56 | for obj in context.selected_objects: 57 | if obj.type == 'MESH': 58 | if hasattr(obj.data, 'use_auto_smooth'): 59 | obj.data.use_auto_smooth = True 60 | 61 | for mod in obj.modifiers[:]: 62 | if mod.type == 'WEIGHTED_NORMAL': 63 | obj.modifiers.remove(mod) 64 | 65 | mod = obj.modifiers.new('WeightedNormal', 'WEIGHTED_NORMAL') 66 | mod.mode = self.mode 67 | mod.weight = self.weight 68 | mod.thresh = self.thresh 69 | mod.keep_sharp = self.keep_sharp 70 | mod.use_face_influence = self.use_face_influence 71 | 72 | return {'FINISHED'} 73 | -------------------------------------------------------------------------------- /addon/props/__init__.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . map_props import SOURCEOPS_MapProps 3 | from . attachment_props import SOURCEOPS_AttachmentProps 4 | from . particle_props import SOURCEOPS_ParticleProps 5 | from . event_props import SOURCEOPS_EventProps 6 | from . sequence_props import SOURCEOPS_SequenceProps 7 | from . skin_props import SOURCEOPS_SkinProps 8 | from . material_folder_props import SOURCEOPS_MaterialFolderProps 9 | from . model_props import SOURCEOPS_ModelProps 10 | from . game_props import SOURCEOPS_GameProps 11 | from . global_props import SOURCEOPS_GlobalProps 12 | from . addon_prefs import SOURCEOPS_AddonPrefs 13 | 14 | 15 | def register(): 16 | bpy.utils.register_class(SOURCEOPS_MapProps) 17 | bpy.utils.register_class(SOURCEOPS_AttachmentProps) 18 | bpy.utils.register_class(SOURCEOPS_ParticleProps) 19 | bpy.utils.register_class(SOURCEOPS_EventProps) 20 | bpy.utils.register_class(SOURCEOPS_SequenceProps) 21 | bpy.utils.register_class(SOURCEOPS_SkinProps) 22 | bpy.utils.register_class(SOURCEOPS_MaterialFolderProps) 23 | bpy.utils.register_class(SOURCEOPS_ModelProps) 24 | bpy.utils.register_class(SOURCEOPS_GameProps) 25 | bpy.utils.register_class(SOURCEOPS_GlobalProps) 26 | bpy.utils.register_class(SOURCEOPS_AddonPrefs) 27 | bpy.types.Scene.sourceops = bpy.props.PointerProperty(type=SOURCEOPS_GlobalProps) 28 | 29 | 30 | def unregister(): 31 | del bpy.types.Scene.sourceops 32 | bpy.utils.unregister_class(SOURCEOPS_AddonPrefs) 33 | bpy.utils.unregister_class(SOURCEOPS_GlobalProps) 34 | bpy.utils.unregister_class(SOURCEOPS_GameProps) 35 | bpy.utils.unregister_class(SOURCEOPS_ModelProps) 36 | bpy.utils.unregister_class(SOURCEOPS_MaterialFolderProps) 37 | bpy.utils.unregister_class(SOURCEOPS_SkinProps) 38 | bpy.utils.unregister_class(SOURCEOPS_SequenceProps) 39 | bpy.utils.unregister_class(SOURCEOPS_EventProps) 40 | bpy.utils.unregister_class(SOURCEOPS_AttachmentProps) 41 | bpy.utils.unregister_class(SOURCEOPS_ParticleProps) 42 | bpy.utils.unregister_class(SOURCEOPS_MapProps) 43 | -------------------------------------------------------------------------------- /addon/props/addon_prefs.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | from .. import utils 4 | from . game_props import SOURCEOPS_GameProps 5 | 6 | 7 | class SOURCEOPS_AddonPrefs(bpy.types.AddonPreferences): 8 | bl_idname = __name__.partition('.')[0] 9 | 10 | wine: bpy.props.StringProperty( 11 | name='Wine', 12 | description='Path to your wine installation', 13 | subtype='FILE_PATH', 14 | update=utils.common.update_wine, 15 | ) 16 | 17 | game_items: bpy.props.CollectionProperty(type=SOURCEOPS_GameProps) 18 | game_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 19 | 20 | def draw(self, context): 21 | layout = self.layout 22 | layout.use_property_split = True 23 | layout.use_property_decorate = False 24 | 25 | if os.name == 'posix': 26 | layout.prop(self, 'wine') 27 | 28 | row = layout.row() 29 | row.operator('sourceops.backup_preferences') 30 | row.operator('sourceops.restore_preferences') 31 | -------------------------------------------------------------------------------- /addon/props/attachment_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_AttachmentProps(bpy.types.PropertyGroup): 5 | name: bpy.props.StringProperty( 6 | name='Name', 7 | description='The name of this attachment', 8 | default='Attachment', 9 | ) 10 | 11 | bone: bpy.props.StringProperty( 12 | name='Bone', 13 | description='The bone that this attachment should attach to', 14 | default='', 15 | ) 16 | 17 | offset: bpy.props.FloatVectorProperty( 18 | name='Offset', 19 | subtype='XYZ', 20 | description='The local X, Y, and Z position of the attachment (relative to the bone position)', 21 | default=(0.0, 0.0, 0.0), 22 | step=10, 23 | precision=3, 24 | ) 25 | 26 | rotation: bpy.props.FloatVectorProperty( 27 | name='Rotation', 28 | subtype='XYZ', 29 | description='Rotates the attachment, in degrees, relative to its parent bone / the origin. Formatted as [pitch, yaw, roll]', 30 | default=(0.0, 0.0, 0.0), 31 | step=100, 32 | precision=3, 33 | ) 34 | 35 | absolute: bpy.props.BoolProperty( 36 | name='Absolute', 37 | description='Parented to the model\'s origin. The offset is still relative to the given parent bone, however', 38 | default=False, 39 | ) 40 | 41 | rigid: bpy.props.BoolProperty( 42 | name='Rigid', 43 | description='Declares that the bone this attachment is parented to will not move, allowing StudioMDL to optimise it out. Used to convert bones created in a modelling package into attachments', 44 | default=False, 45 | ) 46 | -------------------------------------------------------------------------------- /addon/props/event_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_EventProps(bpy.types.PropertyGroup): 5 | name: bpy.props.StringProperty( 6 | name='Name', 7 | description='The name this event has in the list, just for display', 8 | default='Example', 9 | ) 10 | 11 | event: bpy.props.StringProperty( 12 | name='Event Type', 13 | description='The type of the event', 14 | default='AE_CL_PLAYSOUND', 15 | ) 16 | 17 | frame: bpy.props.IntProperty( 18 | name='Start Frame', 19 | description='The frame of the sequence at which the event should start', 20 | default=0, 21 | ) 22 | 23 | value: bpy.props.StringProperty( 24 | name='Event Value', 25 | description='The value for the event', 26 | default='Weapon_Shotgun.Single', 27 | ) 28 | -------------------------------------------------------------------------------- /addon/props/game_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. import utils 3 | 4 | 5 | class SOURCEOPS_GameProps(bpy.types.PropertyGroup): 6 | name: bpy.props.StringProperty( 7 | name='Name', 8 | description='The name this game has in the list, just for display', 9 | default='Example', 10 | ) 11 | 12 | game: bpy.props.StringProperty( 13 | name='Game', 14 | description='Path to your game folder, gameinfo.txt is here', 15 | subtype='DIR_PATH', 16 | update=utils.game.update_game, 17 | ) 18 | 19 | bin: bpy.props.StringProperty( 20 | name='Bin', 21 | description='Path to your bin folder, StudioMDL and HLMV are here', 22 | subtype='DIR_PATH', 23 | update=utils.game.update_bin, 24 | ) 25 | 26 | modelsrc: bpy.props.StringProperty( 27 | name='ModelSrc', 28 | description='Path to your modelsrc folder, exported QC/SMD/FBX files go here', 29 | subtype='DIR_PATH', 30 | update=utils.game.update_modelsrc, 31 | ) 32 | 33 | models: bpy.props.StringProperty( 34 | name='Models', 35 | description='Path to your models folder, compiled MDL files go here', 36 | subtype='DIR_PATH', 37 | update=utils.game.update_models, 38 | ) 39 | 40 | mapsrc: bpy.props.StringProperty( 41 | name='Mapsrc', 42 | description='Path to your mapsrc folder, exported VMF files go here', 43 | subtype='DIR_PATH', 44 | update=utils.game.update_mapsrc, 45 | ) 46 | 47 | mesh_type: bpy.props.EnumProperty( 48 | name='Mesh Type', 49 | description='File type for mesh export', 50 | items=[ 51 | ('SMD', 'SMD', 'Export meshes as SMD'), 52 | ('FBX', 'FBX', 'Export meshes as FBX (only on CS:GO branch)'), 53 | ], 54 | default='SMD', 55 | ) 56 | -------------------------------------------------------------------------------- /addon/props/global_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . model_props import SOURCEOPS_ModelProps 3 | from . map_props import SOURCEOPS_MapProps 4 | 5 | 6 | class SOURCEOPS_GlobalProps(bpy.types.PropertyGroup): 7 | model_items: bpy.props.CollectionProperty(type=SOURCEOPS_ModelProps) 8 | model_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 9 | 10 | map_items: bpy.props.CollectionProperty(type=SOURCEOPS_MapProps) 11 | map_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 12 | 13 | simulation_input: bpy.props.PointerProperty( 14 | name='Simulation Input', 15 | description='The collection containing your rigid body objects', 16 | type=bpy.types.Collection, 17 | ) 18 | 19 | simulation_output: bpy.props.PointerProperty( 20 | name='Simulation Output', 21 | description='The collection your rigged objects will go', 22 | type=bpy.types.Collection, 23 | ) 24 | 25 | panel: bpy.props.EnumProperty( 26 | name='Panel', 27 | description='Which panel to display', 28 | items=[ 29 | ('GAMES', 'Games', 'Display the games panel', 'PREFERENCES', 1), 30 | ('MODELS', 'Models', 'Display the models panel', 'MESH_CUBE', 2), 31 | ('MODEL_OPTIONS', 'Model Options', 'Display the model options panel', 'MODIFIER', 3), 32 | ('TEXTURES', 'Textures', 'Display the textures panel', 'TEXTURE', 4), 33 | ('SEQUENCES', 'Sequences', 'Display the sequences panel', 'SEQUENCE', 5), 34 | ('EVENTS', 'Events', 'Display the events panel', 'ACTION', 6), 35 | ('ATTACHMENTS', 'Attachments', 'Display the attachments panel', 'BONE_DATA', 7), 36 | ('PARTICLES', 'Particles', 'Display the particles panel', 'PARTICLES', 8), 37 | ('MAPS', 'Maps', 'Display the maps panel', 'MOD_BUILD', 9), 38 | ('SIMULATION', 'Simulation', 'Display the simulation panel', 'PHYSICS', 10), 39 | ('MISC', 'Misc', 'Display the misc panel', 'MONKEY', 11), 40 | ], 41 | ) 42 | -------------------------------------------------------------------------------- /addon/props/map_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_MapProps(bpy.types.PropertyGroup): 5 | name: bpy.props.StringProperty( 6 | name='Name', 7 | description='The name of the VMF to overwrite with your displacements', 8 | default='example', 9 | ) 10 | 11 | brush_collection: bpy.props.PointerProperty( 12 | name='Brushes', 13 | description='The collection containing your brush objects', 14 | type=bpy.types.Collection, 15 | ) 16 | 17 | disp_collection: bpy.props.PointerProperty( 18 | name='Displacements', 19 | description='The collection containing your displacement objects', 20 | type=bpy.types.Collection, 21 | ) 22 | 23 | geometry_scale: bpy.props.IntProperty( 24 | name='Geometry Scale', 25 | description='How much the geometry will be scaled, just to allow more convenient modeling', 26 | default=64, 27 | min=1, 28 | max=16384, 29 | ) 30 | 31 | texture_scale: bpy.props.FloatProperty( 32 | name='Texture Scale', 33 | description='Size of one texel in hammer units', 34 | default=1.0, 35 | min=0, 36 | max=64, 37 | step=1, 38 | precision=3, 39 | ) 40 | 41 | lightmap_scale: bpy.props.IntProperty( 42 | name='Lightmap Scale', 43 | description='Hammer units per lightmap luxel on the generated brushes', 44 | default=32, 45 | min=1, 46 | max=16384, 47 | ) 48 | 49 | allow_skewed_textures: bpy.props.BoolProperty( 50 | name='Allow Skewed Textures', 51 | description='Allow non-perpendicular UV axes. Works in Hammer as long as faces are not skewed themselves', 52 | default=False, 53 | ) 54 | 55 | align_to_grid: bpy.props.BoolProperty( 56 | name='Align to Grid', 57 | description='Round brush coordinates to whole numbers. Does not affect displacements or their brushes', 58 | default=True, 59 | ) 60 | -------------------------------------------------------------------------------- /addon/props/material_folder_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_MaterialFolderProps(bpy.types.PropertyGroup): 5 | name: bpy.props.StringProperty( 6 | name='Relative Path', 7 | description='$cdmaterials, the folder inside of which to look for materials, relative to your game\'s materials folder', 8 | default='models/example', 9 | ) 10 | -------------------------------------------------------------------------------- /addon/props/model_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . material_folder_props import SOURCEOPS_MaterialFolderProps 3 | from . skin_props import SOURCEOPS_SkinProps 4 | from . sequence_props import SOURCEOPS_SequenceProps 5 | from . attachment_props import SOURCEOPS_AttachmentProps 6 | from . particle_props import SOURCEOPS_ParticleProps 7 | from . surface_props import SOURCEOPS_SurfaceProps 8 | 9 | 10 | class SOURCEOPS_ModelProps(bpy.types.PropertyGroup): 11 | material_folder_items: bpy.props.CollectionProperty(type=SOURCEOPS_MaterialFolderProps) 12 | material_folder_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 13 | 14 | skin_items: bpy.props.CollectionProperty(type=SOURCEOPS_SkinProps) 15 | skin_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 16 | 17 | sequence_items: bpy.props.CollectionProperty(type=SOURCEOPS_SequenceProps) 18 | sequence_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 19 | 20 | attachment_items: bpy.props.CollectionProperty(type=SOURCEOPS_AttachmentProps) 21 | attachment_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 22 | 23 | particle_items: bpy.props.CollectionProperty(type=SOURCEOPS_ParticleProps) 24 | particle_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 25 | 26 | name: bpy.props.StringProperty( 27 | name='Name', 28 | description='Your model\'s path, eg example/model', 29 | default='example/model', 30 | ) 31 | 32 | rename_material: bpy.props.StringProperty( 33 | name='Rename Material', 34 | description='Rename the first material currently on your model when exporting', 35 | default='', 36 | ) 37 | 38 | def poll_armature(self, object): 39 | return object.type == 'ARMATURE' 40 | 41 | armature: bpy.props.PointerProperty( 42 | name='Armature', 43 | description='Armature that controls the object', 44 | type=bpy.types.Object, 45 | poll=poll_armature, 46 | ) 47 | 48 | def poll_reference(self, object): 49 | return object not in (self.collision, self.bodygroups, self.stacking) 50 | 51 | reference: bpy.props.PointerProperty( 52 | name='Reference', 53 | description='Visible meshes combined into one body', 54 | type=bpy.types.Collection, 55 | poll=poll_reference, 56 | ) 57 | 58 | def poll_collision(self, object): 59 | return object not in (self.reference, self.bodygroups, self.stacking) 60 | 61 | collision: bpy.props.PointerProperty( 62 | name='Collision', 63 | description='Tangible meshes combined into one body', 64 | type=bpy.types.Collection, 65 | poll=poll_collision, 66 | ) 67 | 68 | def poll_bodygroups(self, object): 69 | return object not in (self.reference, self.collision, self.stacking) 70 | 71 | bodygroups: bpy.props.PointerProperty( 72 | name='Bodygroups', 73 | description='Groups of visible meshes, the game can choose one body per group', 74 | type=bpy.types.Collection, 75 | poll=poll_bodygroups, 76 | ) 77 | 78 | def poll_stacking(self, object): 79 | return object not in (self.reference, self.collision, self.bodygroups) 80 | 81 | stacking: bpy.props.PointerProperty( 82 | name='Stacking', 83 | description='Visible meshes drawn in the specified order', 84 | type=bpy.types.Collection, 85 | poll=poll_stacking, 86 | ) 87 | 88 | surface: bpy.props.EnumProperty( 89 | name='Surface Property', 90 | description='$surfaceprop, this affects decals and how it sounds in game', 91 | items=SOURCEOPS_SurfaceProps, 92 | default='default', 93 | ) 94 | 95 | glass: bpy.props.BoolProperty( 96 | name='Has Glass', 97 | description='$mostlyopaque, use this if your model has something transparent like glass', 98 | default=False, 99 | ) 100 | 101 | static: bpy.props.BoolProperty( 102 | name='Static Prop', 103 | description='$staticprop, use this for models with no moving parts.\nRemoves animations and bones, does some optimization.\nWarning: can cause issues such as blank for bodygroups not working', 104 | default=False, 105 | ) 106 | 107 | static_prop_combine: bpy.props.BoolProperty( 108 | name='Static Prop Combine', 109 | description='Whether to use the steamapps/content path instead of modelsrc, necessary for autocombine, a neat CS:GO feature.\nWarning: does not work with $origin', 110 | default=False, 111 | ) 112 | 113 | joints: bpy.props.BoolProperty( 114 | name='Collision Joints', 115 | description='Use $collisionjoints instead of $collisionmodel, recommended for animated models and ragdolls', 116 | default=False, 117 | ) 118 | 119 | prepend_armature: bpy.props.BoolProperty( 120 | name='Prepend Armature', 121 | description='Prepend the name of the armature to every bone name in your SMD files. Necessary for multi-armature models', 122 | default=False, 123 | ) 124 | 125 | ignore_transforms: bpy.props.BoolProperty( 126 | name='Ignore Transforms', 127 | description='Ignores all transforms of all objects, this includes parenting', 128 | default=False, 129 | ) 130 | 131 | origin_source: bpy.props.EnumProperty( 132 | name='Origin Source', 133 | description='Method of specifying $origin.\nEither manually specified in this panel, or via an object', 134 | items=[ 135 | ('MANUAL', 'Manual Input', 'Specify the transforms manually in this panel'), 136 | ('OBJECT', 'Object', 'Use an object\'s transforms\nIf it isn\'t set, then no transforms are used'), 137 | ], 138 | ) 139 | 140 | origin_object: bpy.props.PointerProperty( 141 | name='Origin Object', 142 | description='The object to use the transforms of as the $origin', 143 | type=bpy.types.Object, 144 | ) 145 | 146 | origin_x: bpy.props.FloatProperty( 147 | name='Origin +X', 148 | description='Translation on the X axis for $origin in the QC file', 149 | default=0.0, 150 | ) 151 | 152 | origin_y: bpy.props.FloatProperty( 153 | name='Origin +Y', 154 | description='Translation on the Y axis for $origin in the QC file', 155 | default=0.0, 156 | ) 157 | 158 | origin_z: bpy.props.FloatProperty( 159 | name='Origin Z', 160 | description='Translation on the Z axis for $origin in the QC file', 161 | default=0.0, 162 | ) 163 | 164 | rotation: bpy.props.FloatProperty( 165 | name='Origin Rotation', 166 | description='Rotation around the up axis for $origin in the QC file, this is applied after the location', 167 | default=0.0, 168 | ) 169 | 170 | scale: bpy.props.FloatProperty( 171 | name='Model Scale', 172 | description='$scale to put at the top of your QC files, this does not affect $origin or attachments', 173 | default=1.0, 174 | ) 175 | -------------------------------------------------------------------------------- /addon/props/particle_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | SOURCEOPS_ParticleAttachProps = [ 4 | ('start_at_origin', 'start_at_origin', ''), 5 | ('start_at_attachment', 'start_at_attachment', ''), 6 | ('follow_origin', 'follow_origin', ''), 7 | ('follow_attachment', 'follow_attachment', ''), 8 | ] 9 | 10 | class SOURCEOPS_ParticleProps(bpy.types.PropertyGroup): 11 | name: bpy.props.StringProperty( 12 | name='Name', 13 | description='The name of a particle system. NOT the name of a .pcf file!', 14 | default='Particle', 15 | ) 16 | 17 | attachment_type: bpy.props.EnumProperty( 18 | name='Attachment Type', 19 | description='The method of attaching the particle to the prop', 20 | items=SOURCEOPS_ParticleAttachProps, 21 | default='start_at_origin', 22 | ) 23 | 24 | attachment_point: bpy.props.StringProperty( 25 | name='Attachment Point', 26 | description='The attachment point at which the particle system should spawn, if applicable', 27 | default='', 28 | ) 29 | -------------------------------------------------------------------------------- /addon/props/sequence_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . event_props import SOURCEOPS_EventProps 3 | 4 | 5 | class SOURCEOPS_SequenceProps(bpy.types.PropertyGroup): 6 | event_items: bpy.props.CollectionProperty(type=SOURCEOPS_EventProps) 7 | event_index: bpy.props.IntProperty(default=0, name='Ctrl click to rename') 8 | 9 | name: bpy.props.StringProperty( 10 | name='Name', 11 | description='The name this sequence will have in game', 12 | default='idle', 13 | ) 14 | 15 | action: bpy.props.PointerProperty( 16 | name='Action', 17 | description='The action to use for this sequence', 18 | type=bpy.types.Action, 19 | ) 20 | 21 | use_framerate: bpy.props.BoolProperty( 22 | name='Custom Framerate', 23 | description='Whether to use the custom framerate instead of the scene framerate', 24 | default=False, 25 | ) 26 | 27 | framerate: bpy.props.IntProperty( 28 | name='Framerate', 29 | description='If override is enabled, use this framerate instead of the scene framerate', 30 | default=30, 31 | ) 32 | 33 | use_range: bpy.props.BoolProperty( 34 | name='Custom Range', 35 | description='Whether to use custom start and end frames instead of the whole action', 36 | default=False, 37 | ) 38 | 39 | start: bpy.props.IntProperty( 40 | name='Start Frame', 41 | description='First frame of the sequence', 42 | default=1, 43 | ) 44 | 45 | end: bpy.props.IntProperty( 46 | name='End Frame', 47 | description='Last frame of the sequence', 48 | default=30, 49 | ) 50 | 51 | activity: bpy.props.StringProperty( 52 | name='Activity', 53 | description='The the activity that triggers this sequence to play', 54 | default='ACT_VM_IDLE', 55 | ) 56 | 57 | weight: bpy.props.IntProperty( 58 | name='Weight', 59 | description='Determines the chance this sequence will play compared to other sequences with this activity', 60 | default=1, 61 | ) 62 | 63 | snap: bpy.props.BoolProperty( 64 | name='Snap', 65 | description='Snap to and from this sequence instead of interpolating', 66 | default=False, 67 | ) 68 | 69 | loop: bpy.props.BoolProperty( 70 | name='Loop', 71 | description='Whether the sequence will be looped.\nStart frame must be identical to end frame', 72 | default=False, 73 | ) 74 | -------------------------------------------------------------------------------- /addon/props/skin_props.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_SkinProps(bpy.types.PropertyGroup): 5 | name: bpy.props.StringProperty( 6 | name='Materials', 7 | description='Space separated list of VMT names, supports quotes.\nThe first line must be the materials currently on your model', 8 | default='example', 9 | ) 10 | -------------------------------------------------------------------------------- /addon/props/surface_props.py: -------------------------------------------------------------------------------- 1 | SOURCEOPS_SurfaceProps = sorted([ 2 | ('default', 'default', ''), 3 | ('default_silent', 'default_silent', ''), 4 | ('floatingstandable', 'floatingstandable', ''), 5 | ('item', 'item', ''), 6 | ('ladder', 'ladder', ''), 7 | ('no_decal', 'no_decal', ''), 8 | ('player', 'player', ''), 9 | ('player_control_clip', 'player_control_clip', ''), 10 | ('brick', 'brick', ''), 11 | ('concrete', 'concrete', ''), 12 | ('concrete_block', 'concrete_block', ''), 13 | ('rock', 'rock', ''), 14 | ('canister', 'canister', ''), 15 | ('chain', 'chain', ''), 16 | ('chainlink', 'chainlink', ''), 17 | ('combine_metal', 'combine_metal', ''), 18 | ('crowbar', 'crowbar', ''), 19 | ('floating_metal_barrel', 'floating_metal_barrel', ''), 20 | ('grenade', 'grenade', ''), 21 | ('gunship', 'gunship', ''), 22 | ('metal', 'metal', ''), 23 | ('metal_barrel', 'metal_barrel', ''), 24 | ('metal_bouncy', 'metal_bouncy', ''), 25 | ('metal_box', 'metal_box', ''), 26 | ('metal_seafloorcar', 'metal_seafloorcar', ''), 27 | ('metalgrate', 'metalgrate', ''), 28 | ('metalpanel', 'metalpanel', ''), 29 | ('metalvent', 'metalvent', ''), 30 | ('metalvehicle', 'metalvehicle', ''), 31 | ('paintcan', 'paintcan', ''), 32 | ('popcan', 'popcan', ''), 33 | ('roller', 'roller', ''), 34 | ('slipperymetal', 'slipperymetal', ''), 35 | ('solidmetal', 'solidmetal', ''), 36 | ('strider', 'strider', ''), 37 | ('weapon', 'weapon', ''), 38 | ('wood', 'wood', ''), 39 | ('wood_box', 'wood_box', ''), 40 | ('wood_furniture', 'wood_furniture', ''), 41 | ('wood_plank', 'wood_plank', ''), 42 | ('wood_panel', 'wood_panel', ''), 43 | ('wood_solid', 'wood_solid', ''), 44 | ('dirt', 'dirt', ''), 45 | ('grass', 'grass', ''), 46 | ('gravel', 'gravel', ''), 47 | ('mud', 'mud', ''), 48 | ('quicksand', 'quicksand', ''), 49 | ('sand', 'sand', ''), 50 | ('slipperyslime', 'slipperyslime', ''), 51 | ('antlionsand', 'antlionsand', ''), 52 | ('slime', 'slime', ''), 53 | ('water', 'water', ''), 54 | ('wade', 'wade', ''), 55 | ('ice', 'ice', ''), 56 | ('snow', 'snow', ''), 57 | ('alienflesh', 'alienflesh', ''), 58 | ('antlion', 'antlion', ''), 59 | ('armorflesh', 'armorflesh', ''), 60 | ('bloodyflesh', 'bloodyflesh', ''), 61 | ('flesh', 'flesh', ''), 62 | ('foliage', 'foliage', ''), 63 | ('watermelon', 'watermelon', ''), 64 | ('zombieflesh', 'zombieflesh', ''), 65 | ('glass', 'glass', ''), 66 | ('glassbottle', 'glassbottle', ''), 67 | ('combine_glass', 'combine_glass', ''), 68 | ('tile', 'tile', ''), 69 | ('paper', 'paper', ''), 70 | ('papercup', 'papercup', ''), 71 | ('cardboard', 'cardboard', ''), 72 | ('plaster', 'plaster', ''), 73 | ('plastic_barrel', 'plastic_barrel', ''), 74 | ('plastic_barrel_buoyant', 'plastic_barrel_buoyant', ''), 75 | ('plastic_box', 'plastic_box', ''), 76 | ('plastic', 'plastic', ''), 77 | ('rubber', 'rubber', ''), 78 | ('rubbertire', 'rubbertire', ''), 79 | ('slidingrubbertire', 'slidingrubbertire', ''), 80 | ('slidingrubbertire_front', 'slidingrubbertire_front', ''), 81 | ('slidingrubbertire_rear', 'slidingrubbertire_rear', ''), 82 | ('jeeptire', 'jeeptire', ''), 83 | ('brackingrubbertire', 'brackingrubbertire', ''), 84 | ('carpet', 'carpet', ''), 85 | ('ceiling_tile', 'ceiling_tile', ''), 86 | ('computer', 'computer', ''), 87 | ('pottery', 'pottery', ''), 88 | ]) 89 | -------------------------------------------------------------------------------- /addon/types/__init__.py: -------------------------------------------------------------------------------- 1 | from . import pyvmf 2 | from . import model_export 3 | from . import map_export 4 | -------------------------------------------------------------------------------- /addon/types/map_export/__init__.py: -------------------------------------------------------------------------------- 1 | from . import brush 2 | from . import displacement 3 | from . import vmf 4 | -------------------------------------------------------------------------------- /addon/types/map_export/brush.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bmesh 3 | import mathutils 4 | import math 5 | import typing 6 | from .. pyvmf import pyvmf 7 | 8 | 9 | def sort_into_parts(bm: bmesh.types.BMesh): 10 | parts = [] 11 | 12 | bm.select_mode = {'FACE'} 13 | 14 | for face in bm.faces: 15 | face.hide_set(False) 16 | 17 | while True: 18 | face = next((f for f in bm.faces if not f.hide), None) 19 | 20 | if not face: 21 | break 22 | 23 | faces = set([face]) 24 | 25 | while True: 26 | temp_faces = faces.copy() 27 | 28 | for face in temp_faces: 29 | for edge in face.edges: 30 | faces.update(set(edge.link_faces)) 31 | 32 | if len(temp_faces) == len(faces): 33 | break 34 | 35 | for face in faces: 36 | face.hide_set(True) 37 | 38 | parts.append(faces) 39 | 40 | return parts 41 | 42 | 43 | def get_texture_size(obj: bpy.types.Object, face: bmesh.types.BMFace): 44 | if face.material_index in range(len(obj.material_slots)): 45 | face_material = obj.material_slots[face.material_index].material 46 | 47 | if face_material and face_material.use_nodes: 48 | for mat_node in face_material.node_tree.nodes: 49 | if mat_node.type == 'TEX_IMAGE': 50 | return mat_node.image.size[0] 51 | 52 | return -1 53 | 54 | 55 | def calc_uv_axes(settings: typing.Any, obj: bpy.types.Object, bm: bmesh.types.BMesh, face: bmesh.types.BMFace): 56 | points = [loop.vert.co.copy() for loop in face.loops[0:3]] 57 | 58 | u_vals = [] 59 | v_vals = [] 60 | 61 | if len(bm.loops.layers.uv) > 0: 62 | uv_layer = bm.loops.layers.uv.verify() 63 | 64 | for loop in face.loops[0:3]: 65 | uv = loop[uv_layer].uv 66 | u_vals.append(uv[0]) 67 | v_vals.append(1 - uv[1]) 68 | 69 | else: 70 | u_vals = [0, 0, 1] 71 | v_vals = [0, 1, 1] 72 | 73 | p1, p2, p3 = points 74 | u1, u2, u3 = u_vals 75 | v1, v2, v3 = v_vals 76 | 77 | uv_side_a = mathutils.Vector((u2 - u1, v2 - v1)) 78 | uv_side_b = mathutils.Vector((u3 - u1, v3 - v1)) 79 | tangent = (p2 - p1) * uv_side_b.y - (p3 - p1) * uv_side_a.y 80 | side_v = (p3 - p1) * uv_side_a.x - (p2 - p1) * uv_side_b.x 81 | determinant = uv_side_a.x * uv_side_b.y - uv_side_b.x * uv_side_a.y 82 | 83 | epsilon = 0.0001 84 | 85 | if abs(determinant) > epsilon: 86 | tangent = tangent / determinant 87 | side_v = side_v / determinant 88 | 89 | if not settings.allow_skewed_textures: 90 | bitangent = mathutils.Quaternion(face.normal, math.radians(90)) @ tangent 91 | bitangent.normalize() 92 | bitangent = bitangent * side_v.dot(bitangent) 93 | else: 94 | bitangent = side_v 95 | 96 | # Scale 97 | texture_side_length = get_texture_size(obj, face) 98 | if texture_side_length > 0: 99 | u_scale = tangent.magnitude / texture_side_length 100 | v_scale = bitangent.magnitude / texture_side_length 101 | else: 102 | u_scale = 1 103 | v_scale = 1 104 | 105 | # Offset 106 | tangent_space_transform = mathutils.Matrix(( 107 | [tangent.x, bitangent.x, face.normal.x], 108 | [tangent.y, bitangent.y, face.normal.y], 109 | [tangent.z, bitangent.z, face.normal.z] 110 | )) 111 | if texture_side_length > 0 and abs(tangent_space_transform.determinant()) > epsilon: 112 | tangent_space_transform.invert() 113 | t1 = tangent_space_transform @ p1 114 | u_offset = (1 - (t1.x - u1) * texture_side_length) % texture_side_length 115 | v_offset = (1 - (t1.y - v1) * texture_side_length) % texture_side_length 116 | else: 117 | u_offset = 0 118 | v_offset = 0 119 | 120 | tangent.normalize() 121 | bitangent.normalize() 122 | 123 | u_axis = f'[{tangent[0]} {tangent[1]} {tangent[2]} {u_offset}] {u_scale * settings.texture_scale}' 124 | v_axis = f'[{bitangent[0]} {bitangent[1]} {bitangent[2]} {v_offset}] {v_scale * settings.texture_scale}' 125 | 126 | return u_axis, v_axis 127 | 128 | 129 | def convert_object(settings: typing.Any, obj: bpy.types.Object): 130 | solids = [] 131 | 132 | if obj.type != 'MESH': 133 | print(f'Skipping {obj.name} because it is not a mesh') 134 | return [] 135 | 136 | depsgraph = bpy.context.evaluated_depsgraph_get() 137 | 138 | bm = bmesh.new() 139 | bm.from_object(obj, depsgraph) 140 | 141 | matrix = mathutils.Matrix.Scale(settings.geometry_scale, 4) @ obj.matrix_world 142 | bmesh.ops.transform(bm, matrix=matrix, space=mathutils.Matrix.Identity(4), verts=bm.verts) 143 | 144 | parts = sort_into_parts(bm) 145 | 146 | for part in parts: 147 | solid = pyvmf.Solid() 148 | 149 | for face in part: 150 | side = pyvmf.Side() 151 | 152 | face.normal_flip() 153 | 154 | side.plane.clear() 155 | 156 | for vert in face.verts[0:3]: 157 | vertex = pyvmf.Vertex(*vert.co) 158 | 159 | if settings.align_to_grid: 160 | vertex.align_to_grid() 161 | 162 | side.plane.append(vertex) 163 | 164 | u_axis, v_axis = calc_uv_axes(settings, obj, bm, face) 165 | side.uaxis = pyvmf.Convert.string_to_uvaxis(u_axis) 166 | side.vaxis = pyvmf.Convert.string_to_uvaxis(v_axis) 167 | 168 | side.lightmapscale = settings.lightmap_scale 169 | 170 | try: 171 | side.material = obj.data.materials[face.material_index].name.upper() 172 | except: 173 | side.material = 'tools/toolsnodraw'.upper() 174 | 175 | solid.add_sides(side) 176 | 177 | solid.editor = pyvmf.Editor() 178 | 179 | solids.append(solid) 180 | 181 | bm.free() 182 | 183 | return solids 184 | 185 | 186 | def convert_objects(settings: typing.Any, objects: typing.List[bpy.types.Object]): 187 | solids = [] 188 | 189 | for obj in objects: 190 | result = convert_object(settings, obj) 191 | solids.extend(result) 192 | 193 | return solids 194 | -------------------------------------------------------------------------------- /addon/types/map_export/displacement.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bmesh 3 | import mathutils 4 | import math 5 | import typing 6 | from .. pyvmf import pyvmf 7 | 8 | 9 | def get_levels_and_width(obj: bpy.types.Object): 10 | '''Get the subdivision levels of an object.''' 11 | 12 | # Declare levels 13 | levels = -1 14 | 15 | # Find appropriate modifier and get levels 16 | for mod in obj.modifiers: 17 | 18 | # Multires is supported 19 | if mod.type == 'MULTIRES': 20 | levels = mod.total_levels 21 | break 22 | 23 | # Subsurf is supported 24 | elif mod.type == 'SUBSURF': 25 | levels = mod.levels 26 | break 27 | 28 | # Calculate width from levels 29 | width = 2 ** levels 30 | 31 | # Return levels and width 32 | return levels, width 33 | 34 | 35 | def get_matrix_and_space(obj: bpy.types.Object, scale: float): 36 | '''Get the proper matrix to transform an object.''' 37 | 38 | # Calculate matrix and space 39 | scale = mathutils.Matrix.Scale(scale, 4) 40 | matrix = scale @ obj.matrix_world 41 | space = mathutils.Matrix.Identity(4) 42 | 43 | # Return matrix and space 44 | return matrix, space 45 | 46 | 47 | def setup_subd_mesh(obj: bpy.types.Object, matrix: mathutils.Matrix, space: mathutils.Matrix): 48 | '''Duplicate the mesh and apply transforms.''' 49 | 50 | # Duplicate mesh 51 | obj.data = obj.data.copy() 52 | 53 | # Create bmesh from mesh 54 | bm = bmesh.new() 55 | bm.from_mesh(obj.data) 56 | 57 | # Transform bmesh 58 | bmesh.ops.transform(bm, matrix=matrix, space=space, verts=bm.verts) 59 | 60 | # Apply changes to mesh and free bmesh 61 | bm.to_mesh(obj.data) 62 | bm.free() 63 | 64 | 65 | def align_to_grid(obj: bpy.types.Object): 66 | '''Align the mesh vertices to grid.''' 67 | 68 | # Create bmesh from mesh 69 | bm = bmesh.new() 70 | bm.from_mesh(obj.data) 71 | 72 | # Align verts to grid 73 | for vert in bm.verts: 74 | vert.co.x = round(vert.co.x) 75 | vert.co.y = round(vert.co.y) 76 | vert.co.z = round(vert.co.z) 77 | 78 | # Apply changes to mesh and free bmesh 79 | bm.to_mesh(obj.data) 80 | bm.free() 81 | 82 | 83 | def setup_face_maps(obj: bpy.types.Object): 84 | '''Make a face map for every face of an object.''' 85 | 86 | # Removing existing face maps 87 | obj.face_maps.clear() 88 | 89 | # Declare face maps 90 | face_maps = [] 91 | 92 | # Create face map for every face 93 | for polygon in obj.data.polygons: 94 | face_map = obj.face_maps.new() 95 | face_map.add([polygon.index]) 96 | face_maps.append(face_map) 97 | 98 | # Return face maps 99 | return face_maps 100 | 101 | 102 | def setup_subd_mod(obj: bpy.types.Object, levels: int): 103 | '''Add a subdivision surface modifier to an object.''' 104 | 105 | # Remove existing modifiers 106 | obj.modifiers.clear() 107 | 108 | # Create subsurf modifier 109 | mod = obj.modifiers.new('Subdivision', 'SUBSURF') 110 | 111 | # Set type and levels 112 | mod.subdivision_type = 'SIMPLE' 113 | mod.levels = levels 114 | 115 | # Return subsurf modifier 116 | return mod 117 | 118 | 119 | def setup_uv_layer(obj: bpy.types.Object): 120 | '''Add a reset UV layer to an object.''' 121 | 122 | # Remove existing UV layers 123 | for uv_layer in obj.data.uv_layers[:]: 124 | obj.data.uv_layers.remove(uv_layer) 125 | 126 | # Create new UV layer 127 | uv_layer = obj.data.uv_layers.new() 128 | 129 | # Return UV layer 130 | return uv_layer 131 | 132 | 133 | def calc_uv_axes(a: mathutils.Vector, b: mathutils.Vector, c: mathutils.Vector, texture_scale: float): 134 | '''Calculate U and V axes for brush plane''' 135 | 136 | # Subtract points to calculate edge vectors 137 | one = b - a 138 | two = c - a 139 | 140 | # Calculate normal using cross product of edges 141 | normal = one.cross(two).normalized() 142 | 143 | # Use arbitrary edge as tangent 144 | tangent = -1 * two.normalized() 145 | 146 | # Rotate tangent 90 degrees around normal to calculate bitangent 147 | bitangent = mathutils.Quaternion(normal, math.radians(90)) @ tangent 148 | 149 | # Combine data into strings for VMF export 150 | u_axis = f'[{tangent[0]} {tangent[1]} {tangent[2]} 0] {texture_scale}' 151 | v_axis = f'[{bitangent[0]} {bitangent[1]} {bitangent[2]} 0] {texture_scale}' 152 | 153 | # Return U and V axes 154 | return u_axis, v_axis 155 | 156 | 157 | def convert_object(settings: typing.Any, obj: bpy.types.Object): 158 | '''Convert single object to solids for VMF export.''' 159 | 160 | # Make sure object is mesh 161 | if obj.type != 'MESH': 162 | print(f'Skipping {obj.name} because it is not a mesh') 163 | return [] 164 | 165 | # Make sure all polygons are quads 166 | if any(len(polygon.vertices) != 4 for polygon in obj.data.polygons): 167 | print(f'Skipping {obj.name} because all faces must be quads') 168 | return [] 169 | 170 | # Get levels and width 171 | levels, width = get_levels_and_width(obj) 172 | 173 | # Make sure multires or subsurf mod exists 174 | if levels == -1: 175 | print(f'Skipping {obj.name} because no multires or subsurf modifier was found') 176 | return [] 177 | 178 | # Make sure subdivision levels are in range 179 | if not (2 <= levels <= 4): 180 | print(f'Skipping {obj.name} because subdivision levels must be 2, 3, or 4') 181 | return [] 182 | 183 | # Calculate matrix and space for transform 184 | matrix, space = get_matrix_and_space(obj, settings.geometry_scale) 185 | 186 | # Setup subd object and mesh 187 | obj_subd = obj.copy() 188 | setup_subd_mesh(obj_subd, matrix, space) 189 | 190 | # Setup new UV layer, face maps, and subsurf modifier 191 | uv_layer = setup_uv_layer(obj_subd) 192 | face_maps = setup_face_maps(obj_subd) 193 | mod_subd = setup_subd_mod(obj_subd, levels) 194 | 195 | # Get evaluated dependency graph 196 | depsgraph = bpy.context.evaluated_depsgraph_get() 197 | 198 | # Create bmesh from subdivided object 199 | bm_subd = bmesh.new() 200 | bm_subd.from_object(obj_subd, depsgraph) 201 | 202 | # Get uv layer and face map layer from subd bmesh 203 | uv_subd = bm_subd.loops.layers.uv.verify() 204 | fm_subd = bm_subd.faces.layers.face_map.verify() 205 | 206 | # Create bmesh from sculpted object and transform it 207 | bm_mres = bmesh.new() 208 | bm_mres.from_object(obj, depsgraph) 209 | bmesh.ops.transform(bm_mres, matrix=matrix, space=space, verts=bm_mres.verts) 210 | 211 | # Create bmesh from base mesh 212 | bm_base = bmesh.new() 213 | bm_base.from_mesh(obj.data) 214 | 215 | # Setup displacements list 216 | displacements = [{ 217 | 'levels': levels, 218 | 'corners': [None for i in range(8)], 219 | 'normals': [[None for x in range(width + 1)] for y in range(width + 1)], 220 | 'lengths': [[None for x in range(width + 1)] for y in range(width + 1)], 221 | 'material': 'dev/dev_blendmeasure'.upper(), 222 | } for face_map in face_maps] 223 | 224 | # Populate displacements with data from subd and mres faces 225 | for face_subd, face_mres in zip(bm_subd.faces, bm_mres.faces): 226 | 227 | # Get index for this displacement 228 | z = face_subd[fm_subd] 229 | 230 | # Iterate through loops of each subd and mres face 231 | for loop_subd, loop_mres in zip(face_subd.loops, face_mres.loops): 232 | 233 | # Get row and column for this point 234 | uv = loop_subd[uv_subd].uv 235 | y = round(uv[1] * width) 236 | x = round(uv[0] * width) 237 | 238 | # Get verts for these loops 239 | vert_subd = loop_subd.vert 240 | vert_mres = loop_mres.vert 241 | 242 | # Calculate and write data for this point 243 | vector = vert_mres.co - vert_subd.co 244 | data = displacements[z]['normals'][y][x] = vector.normalized() 245 | data = displacements[z]['lengths'][y][x] = vector.length 246 | 247 | # If this is a corner, store its position 248 | if x == 0 and y == 0: 249 | displacements[z]['corners'][0] = vert_subd.co.copy() 250 | displacements[z]['corners'][4] = vert_subd.co - face_subd.normal * 8 251 | elif x == width and y == 0: 252 | displacements[z]['corners'][1] = vert_subd.co.copy() 253 | displacements[z]['corners'][5] = vert_subd.co - face_subd.normal * 8 254 | elif x == width and y == width: 255 | displacements[z]['corners'][2] = vert_subd.co.copy() 256 | displacements[z]['corners'][6] = vert_subd.co - face_subd.normal * 8 257 | elif x == 0 and y == width: 258 | displacements[z]['corners'][3] = vert_subd.co.copy() 259 | displacements[z]['corners'][7] = vert_subd.co - face_subd.normal * 8 260 | 261 | # Check if mesh has materials 262 | if obj.data.materials: 263 | 264 | # Get displacement materials from base mesh faces 265 | for displacement, face in zip(displacements, bm_base.faces): 266 | material = obj.data.materials[face.material_index] 267 | 268 | # Use material if it exists 269 | if material: 270 | displacement['material'] = material.name.upper() 271 | 272 | # Setup solids list 273 | solids = [] 274 | 275 | # Iterate through displacements 276 | for displacement in displacements: 277 | 278 | # Get brush corners 279 | v1, v2, v3, v4, v5, v6, v7, v8 = displacement['corners'] 280 | 281 | # Create brush sides 282 | f1 = pyvmf.Side(dic={'plane': f'({v1.x} {v1.y} {v1.z}) ({v3.x} {v3.y} {v3.z}) ({v2.x} {v2.y} {v2.z})'}) # Top 283 | f2 = pyvmf.Side(dic={'plane': f'({v7.x} {v7.y} {v7.z}) ({v5.x} {v5.y} {v5.z}) ({v6.x} {v6.y} {v6.z})'}) # Bottom 284 | f3 = pyvmf.Side(dic={'plane': f'({v4.x} {v4.y} {v4.z}) ({v7.x} {v7.y} {v7.z}) ({v3.x} {v3.y} {v3.z})'}) # Front 285 | f4 = pyvmf.Side(dic={'plane': f'({v6.x} {v6.y} {v6.z}) ({v1.x} {v1.y} {v1.z}) ({v2.x} {v2.y} {v2.z})'}) # Back 286 | f5 = pyvmf.Side(dic={'plane': f'({v3.x} {v3.y} {v3.z}) ({v6.x} {v6.y} {v6.z}) ({v2.x} {v2.y} {v2.z})'}) # Right 287 | f6 = pyvmf.Side(dic={'plane': f'({v1.x} {v1.y} {v1.z}) ({v8.x} {v8.y} {v8.z}) ({v4.x} {v4.y} {v4.z})'}) # Left 288 | 289 | # Set U axis, V axis, lightmap scale, and material for top face 290 | f1.uaxis, f1.vaxis = calc_uv_axes(v1, v3, v2, settings.texture_scale) 291 | f1.lightmapscale = settings.lightmap_scale 292 | f1.material = displacement['material'] 293 | 294 | # Prepare dispinfo dictionary 295 | power = displacement['levels'] 296 | startposition = f'[{v1.x} {v1.y} {v1.z}]' 297 | dic = {'power': power, 'startposition': startposition} 298 | 299 | # Prepare dispinfo children 300 | normals = pyvmf.Child('normals', {}) 301 | distances = pyvmf.Child('distances', {}) 302 | children = [normals, distances] 303 | 304 | # Populate dispinfo normals 305 | for index, row in enumerate(displacement['normals']): 306 | normals.dic[f'row{index}'] = ' '.join(f'{x} {y} {z}' for x, y, z in row) 307 | 308 | # Populate dispinfo distances 309 | for index, row in enumerate(displacement['lengths']): 310 | distances.dic[f'row{index}'] = ' '.join(f'{length}' for length in row) 311 | 312 | # Create dispinfo for top face 313 | f1.dispinfo = pyvmf.DispInfo(dic=dic, children=children) 314 | 315 | # Create solid with sides and append it 316 | solid = pyvmf.Solid() 317 | solid.add_sides(f1, f2, f3, f4, f5, f6) 318 | solid.editor = pyvmf.Editor() 319 | solids.append(solid) 320 | 321 | # Free bmeshes 322 | bm_base.free() 323 | bm_mres.free() 324 | bm_subd.free() 325 | 326 | # Remove temporary object and mesh, in that order 327 | mesh_subd = obj_subd.data 328 | bpy.data.objects.remove(obj_subd) 329 | bpy.data.meshes.remove(mesh_subd) 330 | 331 | # Return generated solids 332 | return solids 333 | 334 | 335 | def convert_objects(settings: typing.Any, objects: typing.List[bpy.types.Object]): 336 | '''Convert multiple objects to solids for VMF export.''' 337 | 338 | # Setup solid list 339 | solids = [] 340 | 341 | # Iterate through objects 342 | for obj in objects: 343 | result = convert_object(settings, obj) 344 | solids.extend(result) 345 | 346 | # Return generated solids 347 | return solids 348 | -------------------------------------------------------------------------------- /addon/types/map_export/vmf.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import bmesh 3 | import mathutils 4 | import pathlib 5 | from .. pyvmf import pyvmf 6 | from . import brush 7 | from . import displacement 8 | 9 | 10 | class Settings: 11 | def __init__( 12 | self, 13 | brush_objects, 14 | disp_objects, 15 | geometry_scale, 16 | texture_scale, 17 | lightmap_scale, 18 | allow_skewed_textures, 19 | align_to_grid, 20 | ): 21 | self.brush_objects = brush_objects 22 | self.disp_objects = disp_objects 23 | self.geometry_scale = geometry_scale 24 | self.texture_scale = texture_scale 25 | self.lightmap_scale = lightmap_scale 26 | self.allow_skewed_textures = allow_skewed_textures 27 | self.align_to_grid = align_to_grid 28 | 29 | 30 | class VMF: 31 | def __init__(self, settings: Settings): 32 | scene_settings = self.configure_scene(settings.brush_objects + settings.disp_objects) 33 | 34 | brush_solids = brush.convert_objects(settings, settings.brush_objects) 35 | displacement_solids = displacement.convert_objects(settings, settings.disp_objects) 36 | self.solids = brush_solids + displacement_solids 37 | 38 | self.restore_scene(scene_settings) 39 | 40 | 41 | def export(self, path): 42 | path = pathlib.Path(path).resolve() 43 | path = path.with_suffix('.vmf') 44 | path.parent.mkdir(parents=True, exist_ok=True) 45 | 46 | vmf = pyvmf.new_vmf() 47 | vmf.add_solids(*self.solids) 48 | vmf.export(str(path)) 49 | 50 | 51 | def configure_scene(self, objects): 52 | scene_settings = {o: {} for o in objects} 53 | scene_settings['objects'] = objects 54 | 55 | if bpy.context.active_object: 56 | scene_settings['mode'] = bpy.context.active_object.mode 57 | else: 58 | scene_settings['mode'] = 'OBJECT' 59 | 60 | if scene_settings['mode'] != 'OBJECT': 61 | bpy.ops.object.mode_set(mode='OBJECT') 62 | 63 | for object in objects: 64 | scene_settings[object]['in_scene'] = bpy.context.scene.collection in object.users_collection 65 | if not scene_settings[object]['in_scene']: 66 | bpy.context.scene.collection.objects.link(object) 67 | 68 | scene_settings[object]['hide_viewport'] = True if object.hide_viewport else False 69 | object.hide_viewport = False 70 | 71 | return scene_settings 72 | 73 | 74 | def restore_scene(self, scene_settings): 75 | for object in scene_settings['objects']: 76 | if not scene_settings[object]['in_scene']: 77 | bpy.context.scene.collection.objects.unlink(object) 78 | 79 | object.hide_viewport = scene_settings[object]['hide_viewport'] 80 | 81 | if scene_settings['mode'] != 'OBJECT': 82 | bpy.ops.object.mode_set(mode=scene_settings['mode']) 83 | 84 | 85 | def evaluated_get(self, objects): 86 | evaluated_objects = [] 87 | evaluated_meshes = [] 88 | 89 | for object in objects: 90 | depsgraph = bpy.context.evaluated_depsgraph_get() 91 | evaluated_object = object.evaluated_get(depsgraph) 92 | evaluated_objects.append(evaluated_object) 93 | 94 | evaluated_mesh = evaluated_object.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph) 95 | evaluated_mesh.transform(object.matrix_world) 96 | evaluated_meshes.append(evaluated_mesh) 97 | 98 | return evaluated_objects, evaluated_meshes 99 | 100 | 101 | def to_mesh_clear(self, evaluated_objects): 102 | for object in evaluated_objects: 103 | object.to_mesh_clear() 104 | -------------------------------------------------------------------------------- /addon/types/model_export/__init__.py: -------------------------------------------------------------------------------- 1 | from . import model 2 | from . import smd 3 | from . import fbx 4 | -------------------------------------------------------------------------------- /addon/types/model_export/fbx.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from bpy.types import Bone, Object, PoseBone, TriangulateModifier 3 | from mathutils import Matrix 4 | from pathlib import Path 5 | from typing import List 6 | 7 | 8 | MESH_TYPES = {'CURVE', 'FONT', 'MESH', 'SURFACE'} 9 | OBJECT_TYPES = MESH_TYPES | {'ARMATURE'} 10 | 11 | 12 | def export_fbx(path: Path, armature: Object, objects: List[Object], prepend_armature: bool, ignore_transforms: bool): 13 | '''Export objects to FBX with settings for Source.''' 14 | frame_current = bpy.context.scene.frame_current 15 | bpy.context.scene.frame_current = bpy.context.scene.frame_start 16 | 17 | collection = bpy.data.collections.new('SourceOps') 18 | bpy.context.scene.collection.children.link(collection) 19 | 20 | active_layer_collection = bpy.context.view_layer.active_layer_collection 21 | bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[-1] 22 | 23 | if armature and armature.animation_data and armature.animation_data.action: 24 | action = armature.animation_data.action 25 | armature.animation_data_clear() 26 | 27 | for pose_bone in armature.pose.bones: 28 | pose_bone: PoseBone 29 | bone: Bone = pose_bone.bone 30 | pose_bone.matrix = bone.matrix_local 31 | else: 32 | action = None 33 | 34 | obj_hide_viewport = {} 35 | obj_matrix_local = {} 36 | obj_matrix_parent_inverse = {} 37 | bone_name = {} 38 | obj_triangulate_mod = {} 39 | 40 | if armature: 41 | objects.append(armature) 42 | 43 | for obj in set(objects): 44 | if obj.type in OBJECT_TYPES: 45 | collection.objects.link(obj) 46 | obj_hide_viewport[obj] = obj.hide_viewport 47 | obj.hide_viewport = False 48 | 49 | if ignore_transforms: 50 | obj_matrix_local[obj] = obj.matrix_local.copy() 51 | obj.matrix_local = Matrix.Identity(4) 52 | obj_matrix_parent_inverse[obj] = obj.matrix_parent_inverse.copy() 53 | obj.matrix_parent_inverse = Matrix.Identity(4) 54 | 55 | if obj.type == 'ARMATURE': 56 | if prepend_armature: 57 | for bone in obj.data.bones: 58 | bone_name[bone] = bone.name 59 | bone.name = f'{obj.name}.{bone.name}' 60 | 61 | if obj.type in MESH_TYPES: 62 | mod: TriangulateModifier = obj.modifiers.new('Triangulate', 'TRIANGULATE') 63 | obj_triangulate_mod[obj] = mod 64 | mod.min_vertices = 4 65 | mod.quad_method = 'FIXED' 66 | mod.ngon_method = 'CLIP' 67 | if hasattr(mod, 'keep_custom_normals'): 68 | mod.keep_custom_normals = True 69 | 70 | try: 71 | bpy.ops.export_scene.fbx( 72 | filepath=str(path), 73 | use_active_collection=True, 74 | global_scale=0.01, 75 | add_leaf_bones=False, 76 | bake_anim=False, 77 | ) 78 | 79 | except: 80 | raise 81 | 82 | finally: 83 | for obj, triangulate_mod in obj_triangulate_mod.items(): 84 | obj.modifiers.remove(triangulate_mod) 85 | 86 | if prepend_armature: 87 | for bone, name in bone_name.items(): 88 | bone.name = name 89 | 90 | if ignore_transforms: 91 | for obj, matrix_parent_inverse in obj_matrix_parent_inverse.items(): 92 | obj.matrix_parent_inverse = matrix_parent_inverse 93 | 94 | for obj, matrix_local in obj_matrix_local.items(): 95 | obj.matrix_local = matrix_local 96 | 97 | for obj, hide_viewport in obj_hide_viewport.items(): 98 | obj.hide_viewport = hide_viewport 99 | 100 | if action: 101 | armature.animation_data_create() 102 | armature.animation_data.action = action 103 | 104 | bpy.context.view_layer.active_layer_collection = active_layer_collection 105 | bpy.data.collections.remove(collection) 106 | bpy.context.scene.frame_current = frame_current 107 | -------------------------------------------------------------------------------- /addon/types/model_export/model.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import time 3 | import subprocess 4 | import os 5 | from math import degrees 6 | from shutil import move 7 | from pathlib import Path 8 | from traceback import print_exc 9 | from ... utils import common 10 | from . smd import SMD 11 | from . fbx import export_fbx 12 | 13 | 14 | class Model: 15 | def __init__(self, game, model): 16 | self.prefs = common.get_prefs(bpy.context) 17 | self.wine = Path(self.prefs.wine) 18 | 19 | self.game = Path(game.game) 20 | self.bin = Path(game.bin) 21 | if model.static and model.static_prop_combine: 22 | self.modelsrc = self.game.parent.parent.joinpath('content', self.game.name, 'models') 23 | else: 24 | self.modelsrc = Path(game.modelsrc) 25 | self.models = Path(game.models) 26 | self.mapsrc = Path(game.mapsrc) 27 | self.mesh_type = game.mesh_type 28 | 29 | self.name = Path(model.name).with_suffix('').as_posix() 30 | self.stem = common.clean_filename(Path(self.name).stem) 31 | if model.static and model.static_prop_combine: 32 | directory = self.modelsrc.joinpath(self.name).parent 33 | else: 34 | directory = self.modelsrc.joinpath(self.name) 35 | self.directory = common.verify_folder(directory) 36 | 37 | studiomdl = self.bin.joinpath('studiomdl.exe') 38 | quickmdl = self.bin.joinpath('quickmdl.exe') 39 | self.studiomdl = quickmdl if quickmdl.is_file() else studiomdl 40 | 41 | hlvm = self.bin.joinpath('hlmv.exe') 42 | hlvmplusplus = self.bin.joinpath('hlmvplusplus.exe') 43 | self.hlmv = hlvmplusplus if hlvmplusplus.is_file() else hlvm 44 | 45 | self.material_folder_items = model.material_folder_items 46 | self.skin_items = model.skin_items 47 | self.sequence_items = model.sequence_items 48 | self.attachment_items = model.attachment_items 49 | self.particle_items = model.particle_items 50 | 51 | self.armature = model.armature 52 | self.reference = model.reference 53 | self.collision = model.collision 54 | self.bodygroups = model.bodygroups 55 | self.stacking = model.stacking 56 | 57 | self.rename_material = model.rename_material 58 | self.surface = model.surface 59 | self.glass = model.glass 60 | self.static = model.static 61 | self.static_prop_combine = model.static_prop_combine 62 | self.joints = model.joints 63 | 64 | self.prepend_armature = model.prepend_armature 65 | self.ignore_transforms = model.ignore_transforms 66 | 67 | self.origin_source = model.origin_source 68 | self.origin_object = model.origin_object 69 | 70 | self.origin_x = model.origin_x 71 | self.origin_y = model.origin_y 72 | self.origin_z = model.origin_z 73 | self.rotation = model.rotation 74 | self.scale = model.scale 75 | 76 | def export_meshes(self): 77 | self.ensure_modelsrc_folder() 78 | # self.remove_modelsrc_old() # Commented out because it might be annoying. 79 | 80 | if not self.sequence_items: 81 | self.export_anim(self.armature, None, self.directory.joinpath('anims', 'idle.SMD')) 82 | 83 | for sequence in self.sequence_items: 84 | path = self.directory.joinpath('anims', f'{common.clean_filename(sequence.name)}.SMD') 85 | self.export_anim(self.armature, sequence.action, path) 86 | 87 | if self.reference: 88 | objects = self.get_all_objects(self.reference) 89 | path = self.get_body_path(self.reference) 90 | self.export_mesh(self.armature, objects, path) 91 | 92 | if self.collision: 93 | objects = self.get_all_objects(self.collision) 94 | path = self.get_body_path(self.collision) 95 | self.export_mesh(self.armature, objects, path) 96 | 97 | if self.bodygroups: 98 | for bodygroup in self.bodygroups.children: 99 | for collection in bodygroup.children: 100 | objects = self.get_all_objects(collection) 101 | path = self.get_body_path(collection) 102 | self.export_mesh(self.armature, objects, path) 103 | 104 | if self.stacking: 105 | for collection in self.stacking.children: 106 | objects = self.get_all_objects(collection) 107 | path = self.get_body_path(collection) 108 | self.export_mesh(self.armature, objects, path) 109 | 110 | def export_anim(self, armature, action, path): 111 | self.export_smd(armature, [], action, path) 112 | 113 | def export_mesh(self, armature, objects, path): 114 | if self.mesh_type == 'SMD': 115 | self.export_smd(armature, objects, None, path) 116 | elif self.mesh_type == 'FBX': 117 | self.export_fbx(armature, objects, path) 118 | 119 | def export_smd(self, armature, objects, action, path): 120 | try: 121 | smd_file = path.open('w') 122 | except: 123 | self.report(f'Failed to export: {path}', exception=True) 124 | else: 125 | start = time.time() 126 | 127 | smd = SMD(self.prepend_armature, self.ignore_transforms) 128 | smd.from_blender(armature, objects, action) 129 | 130 | smd_file.write(smd.to_string()) 131 | smd_file.close() 132 | 133 | print(f'Exported: {path} in {round(time.time() - start, 1)} seconds') 134 | 135 | def export_fbx(self, armature, objects, path): 136 | start = time.time() 137 | 138 | try: 139 | export_fbx(path, armature, objects, self.prepend_armature, self.ignore_transforms) 140 | except: 141 | self.report(f'Failed to export: {path}', exception=True) 142 | else: 143 | print(f'Exported: {path} in {round(time.time() - start, 1)} seconds') 144 | 145 | def get_all_objects(self, collection): 146 | return common.remove_duplicates(collection.all_objects) if collection else [] 147 | 148 | def get_body_path(self, collection): 149 | name = common.clean_filename(collection.name) 150 | return self.directory.joinpath(f'{name}.{self.mesh_type}') 151 | 152 | def generate_qc(self): 153 | if not self.reference and not self.stacking: 154 | return self.report(f'Unable to generate QC for: {self.name} (reference and stacking both not set)') 155 | 156 | if not self.armature and not self.static: 157 | self.static = True 158 | print(f'Armature not set for {self.name}, using static') 159 | 160 | self.ensure_modelsrc_folder() 161 | path = self.directory.joinpath(f'{self.stem}.qc') 162 | 163 | try: 164 | qc = path.open('w') 165 | print(f'Generating: {path}') 166 | except: 167 | return self.report(f'Failed to open: {path}', exception=True) 168 | 169 | qc.write(f'$modelname "{self.name}"') 170 | qc.write('\n') 171 | 172 | if not self.material_folder_items: 173 | qc.write('\n') 174 | qc.write('$cdmaterials "/"') 175 | qc.write('\n') 176 | 177 | for material_folder in self.material_folder_items: 178 | qc.write('\n') 179 | qc.write(f'$cdmaterials "{material_folder.name}"') 180 | qc.write('\n') 181 | 182 | qc.write('\n') 183 | qc.write(f'$surfaceprop "{self.surface}"') 184 | qc.write('\n') 185 | 186 | if self.glass: 187 | qc.write('\n') 188 | qc.write('$mostlyopaque') 189 | qc.write('\n') 190 | 191 | if self.static: 192 | qc.write('\n') 193 | qc.write('$staticprop') 194 | qc.write('\n') 195 | 196 | if self.origin_source == 'MANUAL': 197 | origin_x = self.origin_x 198 | origin_y = self.origin_y 199 | origin_z = self.origin_z 200 | rotation = -self.rotation 201 | elif self.origin_source == 'OBJECT' and self.origin_object: 202 | loc, rot, _ = self.origin_object.matrix_world.decompose() 203 | origin_x = loc.x 204 | origin_y = loc.y 205 | origin_z = loc.z 206 | rotation = -degrees(rot.to_euler().z) 207 | else: 208 | origin_x = 0 209 | origin_y = 0 210 | origin_z = 0 211 | rotation = 0 212 | 213 | if self.static and self.mesh_type == 'FBX': 214 | origin_x, origin_y = -origin_y, origin_x 215 | rotation -= 180 216 | else: 217 | rotation -= 90 218 | 219 | # The origin command does not work with static prop combine. 220 | if not (self.static and self.static_prop_combine): 221 | qc.write('\n') 222 | qc.write(f'$origin {origin_x:.6f} {origin_y:.6f} {origin_z:.6f} {rotation:.6f}') 223 | qc.write('\n') 224 | 225 | qc.write('\n') 226 | qc.write(f'$scale {self.scale:.6f}') 227 | qc.write('\n') 228 | 229 | if self.reference: 230 | qc.write('\n') 231 | name = common.clean_filename(self.reference.name) 232 | qc.write(f'$body "{name}" "{name}.{self.mesh_type}"') 233 | qc.write('\n') 234 | 235 | if not self.rename_material == '': 236 | qc.write('\n') 237 | qc.write(f'$renamematerial {self.rename_material}') 238 | qc.write('\n') 239 | 240 | if self.collision: 241 | qc.write('\n') 242 | name = common.clean_filename(self.collision.name) 243 | command = 'collisionjoints' if self.joints else 'collisionmodel' 244 | qc.write(f'${command} "{name}.{self.mesh_type}"' + ' {\n') 245 | command = 'concaveperjoint' if self.joints else 'concave' 246 | qc.write(f' ${command}\n') 247 | qc.write(' $maxconvexpieces 10000\n') 248 | qc.write('}') 249 | qc.write('\n') 250 | 251 | if self.bodygroups: 252 | for bodygroup in self.bodygroups.children: 253 | qc.write('\n') 254 | bodygroup_name = common.clean_filename(bodygroup.name) 255 | qc.write(f'$bodygroup "{bodygroup_name}"' + ' {\n') 256 | for collection in bodygroup.children: 257 | name = common.clean_filename(collection.name) 258 | qc.write(f' studio "{name}.{self.mesh_type}"\n') 259 | qc.write('}') 260 | qc.write('\n') 261 | 262 | if self.stacking: 263 | for collection in self.stacking.children: 264 | qc.write('\n') 265 | name = common.clean_filename(collection.name) 266 | qc.write(f'$model "{name}" "{name}.{self.mesh_type}"') 267 | qc.write('\n') 268 | 269 | if not self.sequence_items: 270 | qc.write('\n') 271 | qc.write(f'$sequence "idle" "anims/idle.SMD"') 272 | qc.write('\n') 273 | 274 | for sequence in self.sequence_items: 275 | qc.write('\n') 276 | qc.write(f'$sequence "{sequence.name}"' + ' {\n') 277 | qc.write(f' "anims/{common.clean_filename(sequence.name)}.SMD"\n') 278 | if sequence.use_framerate: 279 | qc.write(f' fps {sequence.framerate}\n') 280 | else: 281 | qc.write(f' fps {bpy.context.scene.render.fps}\n') 282 | if sequence.use_range: 283 | qc.write(f' frames {sequence.start} {sequence.end}\n') 284 | if sequence.snap: 285 | qc.write(' snap\n') 286 | if sequence.loop: 287 | qc.write(' loop\n') 288 | qc.write(f' activity "{sequence.activity}" {sequence.weight}\n') 289 | for event in sequence.event_items: 290 | qc.write(' { ' + f'event "{event.event}" {event.frame} "{event.value}"' + ' }\n') 291 | qc.write('}') 292 | qc.write('\n') 293 | 294 | for attachment in self.attachment_items: 295 | if self.armature and attachment.bone: 296 | qc.write('\n') 297 | qc.write(f'$attachment "{attachment.name}"') 298 | if self.prepend_armature: 299 | qc.write(f' "{self.armature.name}.{attachment.bone}"') 300 | else: 301 | qc.write(f' "{attachment.bone}"') 302 | qc.write(f' {attachment.offset[0]} {attachment.offset[1]} {attachment.offset[2]}') 303 | if attachment.absolute: 304 | qc.write(' absolute') 305 | if attachment.rigid: 306 | qc.write(' rigid') 307 | qc.write(f' rotate {attachment.rotation[0]} {attachment.rotation[1]} {attachment.rotation[2]}') 308 | qc.write('\n') 309 | 310 | if self.skin_items: 311 | qc.write('\n') 312 | qc.write('$texturegroup "skinfamilies"') 313 | qc.write('\n') 314 | qc.write('{') 315 | 316 | for skin in self.skin_items: 317 | qc.write('\n') 318 | qc.write(f' {{ {skin.name} }}') 319 | 320 | qc.write('\n') 321 | qc.write('}') 322 | qc.write('\n') 323 | 324 | if(len(self.particle_items) > 0): 325 | qc.write('\n') 326 | qc.write('$keyvalues') 327 | qc.write('\n') 328 | qc.write('{') 329 | qc.write('\n') 330 | qc.write(' particles') 331 | qc.write('\n') 332 | qc.write(' {') 333 | 334 | for index, particle in enumerate(self.particle_items): 335 | qc.write('\n') 336 | qc.write(f' "effect{index}"') 337 | qc.write('\n {\n') 338 | qc.write(f' "name" "{particle.name}"') 339 | qc.write('\n') 340 | qc.write(f' "attachment_type" "{particle.attachment_type}"') 341 | qc.write('\n') 342 | if(particle.attachment_point): 343 | qc.write(f' "attachment_point" "{particle.attachment_point}"') 344 | qc.write('\n') 345 | qc.write(' }\n') 346 | 347 | qc.write(' }') 348 | qc.write('\n') 349 | qc.write('}') 350 | 351 | qc.close() 352 | 353 | def compile_qc(self): 354 | qc = self.directory.joinpath(f'{self.stem}.qc') 355 | if qc.is_file(): 356 | print(f'Compiling: {qc}') 357 | self.ensure_models_folder() 358 | self.remove_models_old() 359 | 360 | # Use wine to run StudioMDL on Linux. 361 | # Wine tends to complain about the paths we feed StudioMDL. 362 | # So we use relatve paths working from the base directory of the game. 363 | if (os.name == 'posix') and (self.studiomdl.suffix == '.exe'): 364 | cwd = self.game.parent 365 | args = [str(self.wine), str(self.studiomdl.relative_to(cwd)), '-nop4', '-fullcollide', 366 | '-game', str(self.game.relative_to(cwd)), str(qc.relative_to(cwd))] 367 | else: 368 | cwd = None 369 | args = [str(self.studiomdl), '-nop4', '-fullcollide', '-game', str(self.game), str(qc)] 370 | 371 | pipe = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) 372 | 373 | while True: 374 | code = pipe.returncode 375 | if code is None: 376 | log = self.directory.joinpath(f'{self.stem}.log') 377 | log.write_bytes(b'\n\n\n'.join(pipe.communicate())) 378 | else: 379 | break 380 | 381 | if code == 0: 382 | self.move_files() 383 | else: 384 | return self.report(f'Failed to compile: {qc}') 385 | else: 386 | return self.report(f'Unable to find: {qc}') 387 | 388 | def open_folder(self): 389 | try: 390 | print(f'Opening: {self.directory}') 391 | bpy.ops.wm.path_open(filepath=str(self.directory)) 392 | except: 393 | return self.report(f'Failed to open: {self.directory}', exception=True) 394 | 395 | def view_model(self): 396 | model = self.models.joinpath(self.name) 397 | mdl = model.with_suffix('.mdl') 398 | dx90 = model.with_suffix('.dx90.vtx') 399 | 400 | # Use wine to run HLMV on Linux. 401 | # Wine tends to complain about the paths we feed HLMV. 402 | # So we use relatve paths working from the base directory of the game. 403 | if (os.name == 'posix') and (self.studiomdl.suffix == '.exe'): 404 | cwd = self.game.parent 405 | args = [str(self.wine), str(self.hlmv.relative_to(cwd)), '-game', 406 | str(self.game.relative_to(cwd)), str(mdl.relative_to(cwd))] 407 | else: 408 | cwd = None 409 | args = [str(self.hlmv), '-game', str(self.game), str(mdl)] 410 | 411 | if dx90.is_file(): 412 | print(f'Viewing: {mdl}') 413 | subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) 414 | else: 415 | return self.report(f'Failed to view: {mdl}') 416 | 417 | def move_files(self): 418 | path_src = self.game.joinpath('models', self.name) 419 | path_dst = self.models.joinpath(self.name) 420 | 421 | if path_src == path_dst: 422 | return 423 | 424 | print(f'Moving to: {self.models}') 425 | common.verify_folder(path_dst.parent) 426 | 427 | for suffix in ('.dx90.vtx', '.dx80.vtx', '.sw.vtx', '.vvd', '.mdl', '.phy'): 428 | src = path_src.with_suffix(suffix) 429 | dst = path_dst.with_suffix(suffix) 430 | 431 | try: 432 | move(src, dst) 433 | except: 434 | self.report(f'Failed to move {src} to {dst}', exception=True) 435 | 436 | def ensure_modelsrc_folder(self): 437 | self.directory.mkdir(parents=True, exist_ok=True) 438 | self.directory.joinpath('anims').mkdir(parents=True, exist_ok=True) 439 | 440 | def remove_modelsrc_old(self): 441 | for file in self.directory.rglob('*'): 442 | if file.suffix in ('.SMD', '.FBX'): 443 | if file.is_file(): 444 | file.unlink() 445 | 446 | def ensure_models_folder(self): 447 | destination = self.models.joinpath(self.name).parent 448 | destination.mkdir(parents=True, exist_ok=True) 449 | 450 | def remove_models_old(self): 451 | model = self.models.joinpath(self.name) 452 | for suffix in ('.dx90.vtx', '.dx80.vtx', '.sw.vtx', '.vvd', '.mdl', '.phy'): 453 | path = model.with_suffix(suffix) 454 | if path.is_file(): 455 | path.unlink() 456 | 457 | def report(self, message, exception=False): 458 | print(message) 459 | 460 | if exception: 461 | print_exc() 462 | 463 | return message 464 | -------------------------------------------------------------------------------- /addon/types/model_export/smd.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from typing import List 3 | 4 | 5 | class Settings: 6 | def __init__(self, prepend_armature: bool, ignore_transforms: bool): 7 | self.prepend_armature = prepend_armature 8 | self.ignore_transforms = ignore_transforms 9 | 10 | 11 | class Lookup: 12 | def __init__(self, settings: Settings): 13 | self.settings = settings 14 | 15 | if self.settings.prepend_armature: 16 | name = 'Source.Implicit' 17 | else: 18 | name = 'Implicit' 19 | 20 | self.bones = [name] 21 | 22 | def __getitem__(self, key: str) -> int: 23 | if key in self.bones: 24 | return self.bones.index(key) 25 | else: 26 | return -1 27 | 28 | def from_blender(self, armature: bpy.types.Object): 29 | if armature: 30 | for bone in armature.data.bones: 31 | bone: bpy.types.Bone 32 | 33 | if self.settings.prepend_armature: 34 | name = f'{armature.name}.{bone.name}' 35 | else: 36 | name = bone.name 37 | 38 | self.bones.append(name) 39 | 40 | 41 | class Node: 42 | def __init__(self, settings: Settings): 43 | self.settings = settings 44 | self.index = 0 45 | 46 | if self.settings.prepend_armature: 47 | name = 'Source.Implicit' 48 | else: 49 | name = 'Implicit' 50 | 51 | self.name = name 52 | self.parent = -1 53 | 54 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.Bone): 55 | if self.settings.prepend_armature: 56 | name = f'{armature.name}.{bone.name}' 57 | else: 58 | name = bone.name 59 | 60 | if bone.parent: 61 | if self.settings.prepend_armature: 62 | parent = lookup[f'{armature.name}.{bone.parent.name}'] 63 | else: 64 | parent = lookup[bone.parent.name] 65 | else: 66 | parent = -1 67 | 68 | self.index = lookup[name] 69 | self.name = name 70 | self.parent = parent 71 | 72 | def to_string(self) -> str: 73 | return f'{self.index} "{self.name}" {self.parent}\n' 74 | 75 | 76 | class Nodes: 77 | def __init__(self, settings: Settings): 78 | self.settings = settings 79 | self.nodes = [Node(self.settings)] 80 | 81 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object): 82 | if armature: 83 | for bone in armature.data.bones: 84 | bone: bpy.types.Bone 85 | 86 | node = Node(self.settings) 87 | node.from_blender(lookup, armature, bone) 88 | self.nodes.append(node) 89 | 90 | def to_string(self) -> str: 91 | header = f'nodes\n' 92 | nodes = ''.join(bone.to_string() for bone in self.nodes) 93 | footer = f'end\n' 94 | return f'{header}{nodes}{footer}' 95 | 96 | 97 | class RestBone: 98 | def __init__(self, settings: Settings): 99 | self.settings = settings 100 | self.index = 0 101 | self.translation = [0, 0, 0] 102 | self.rotation = [0, 0, 0] 103 | 104 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.Bone): 105 | if self.settings.prepend_armature: 106 | name = f'{armature.name}.{bone.name}' 107 | else: 108 | name = bone.name 109 | 110 | if bone.parent: 111 | parent = bone.parent.matrix_local.inverted_safe() 112 | matrix = parent @ bone.matrix_local 113 | 114 | elif not self.settings.ignore_transforms: 115 | transforms = armature.matrix_world 116 | matrix = transforms @ bone.matrix_local 117 | 118 | else: 119 | matrix = bone.matrix_local 120 | 121 | self.index = lookup[name] 122 | self.translation = matrix.to_translation()[0:3] 123 | self.rotation = matrix.to_euler()[0:3] 124 | 125 | def to_string(self) -> str: 126 | index = f'{self.index}' 127 | translation = ' '.join(f'{n:.6f}' for n in self.translation) 128 | rotation = ' '.join(f'{n:.6f}' for n in self.rotation) 129 | return f'{index} {translation} {rotation}\n' 130 | 131 | 132 | class RestFrame: 133 | def __init__(self, settings: Settings): 134 | self.settings = settings 135 | self.bones = [RestBone(self.settings)] 136 | 137 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object): 138 | for bone in armature.data.bones: 139 | bone: bpy.types.Bone 140 | 141 | rest_bone = RestBone(self.settings) 142 | rest_bone.from_blender(lookup, armature, bone) 143 | self.bones.append(rest_bone) 144 | 145 | def to_string(self) -> str: 146 | time = f'time 0\n' 147 | bones = ''.join(bone.to_string() for bone in self.bones) 148 | return f'{time}{bones}' 149 | 150 | 151 | class PoseBone: 152 | def __init__(self, settings: Settings): 153 | self.settings = settings 154 | self.index = 0 155 | self.translation = [0, 0, 0] 156 | self.rotation = [0, 0, 0] 157 | 158 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.PoseBone): 159 | if self.settings.prepend_armature: 160 | name = f'{armature.name}.{bone.name}' 161 | else: 162 | name = bone.name 163 | 164 | if bone.parent: 165 | parent = bone.parent.matrix.inverted_safe() 166 | matrix = parent @ bone.matrix 167 | 168 | elif not self.settings.ignore_transforms: 169 | transforms = armature.matrix_world 170 | matrix = transforms @ bone.matrix 171 | 172 | else: 173 | matrix = bone.matrix 174 | 175 | self.index = lookup[name] 176 | self.translation = matrix.to_translation()[0:3] 177 | self.rotation = matrix.to_euler()[0:3] 178 | 179 | def to_string(self) -> str: 180 | index = f'{self.index}' 181 | translation = ' '.join(f'{n:.6f}' for n in self.translation) 182 | rotation = ' '.join(f'{n:.6f}' for n in self.rotation) 183 | return f'{index} {translation} {rotation}\n' 184 | 185 | 186 | class PoseFrame: 187 | def __init__(self, settings: Settings): 188 | self.settings = settings 189 | self.time = 0 190 | self.bones = [PoseBone(self.settings)] 191 | 192 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, time: int): 193 | self.time = time 194 | 195 | for bone in armature.pose.bones: 196 | bone: bpy.types.PoseBone 197 | 198 | pose_bone = PoseBone(self.settings) 199 | pose_bone.from_blender(lookup, armature, bone) 200 | self.bones.append(pose_bone) 201 | 202 | def to_string(self) -> str: 203 | time = f'time {self.time}\n' 204 | bones = ''.join(bone.to_string() for bone in self.bones) 205 | return f'{time}{bones}' 206 | 207 | 208 | class Skeleton: 209 | def __init__(self, settings: Settings): 210 | self.settings = settings 211 | self.frames = [] 212 | 213 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, action: bpy.types.Action): 214 | if not armature: 215 | frame = RestFrame(self.settings) 216 | self.frames.append(frame) 217 | 218 | elif not action: 219 | frame = RestFrame(self.settings) 220 | frame.from_blender(lookup, armature) 221 | self.frames.append(frame) 222 | 223 | else: 224 | if not armature.animation_data: 225 | new_animation_data = armature.animation_data_create() 226 | else: 227 | new_animation_data = None 228 | 229 | original_action = armature.animation_data.action 230 | armature.animation_data.action = action 231 | 232 | if not original_action: 233 | pose_backup = {} 234 | 235 | for pose_bone in armature.pose.bones: 236 | pose_bone: bpy.types.PoseBone 237 | pose_backup[pose_bone] = pose_bone.matrix.copy() 238 | 239 | original_frame = bpy.context.scene.frame_current 240 | 241 | start = max(0, int(action.frame_range[0])) 242 | end = max(0, int(action.frame_range[1])) 243 | 244 | for time in range(start, end + 1): 245 | bpy.context.scene.frame_set(time) 246 | 247 | frame = PoseFrame(self.settings) 248 | frame.from_blender(lookup, armature, time) 249 | self.frames.append(frame) 250 | 251 | bpy.context.scene.frame_set(original_frame) 252 | 253 | if not original_action: 254 | for pose_bone, matrix in pose_backup.items(): 255 | pose_bone.matrix = matrix 256 | 257 | if new_animation_data: 258 | armature.animation_data_clear() 259 | else: 260 | armature.animation_data.action = original_action 261 | 262 | def to_string(self) -> str: 263 | header = f'skeleton\n' 264 | frames = ''.join(frame.to_string() for frame in self.frames) 265 | footer = f'end\n' 266 | return f'{header}{frames}{footer}' 267 | 268 | 269 | class Vertex: 270 | def __init__(self, settings: Settings): 271 | self.settings = settings 272 | self.coords = [0, 0, 0] 273 | self.normal = [0, 0, 0] 274 | self.uvs = [0, 0] 275 | self.bones = [] 276 | 277 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object, mesh: bpy.types.Mesh, loop: bpy.types.MeshLoop): 278 | vertex = mesh.vertices[loop.vertex_index] 279 | self.coords = vertex.co[0:3] 280 | self.normal = loop.normal[0:3] 281 | 282 | if mesh.uv_layers: 283 | self.uvs = mesh.uv_layers.active.data[loop.index].uv[0:2] 284 | else: 285 | self.uvs = [0.0, 0.0] 286 | 287 | if armature: 288 | for group in vertex.groups: 289 | group: bpy.types.VertexGroupElement 290 | 291 | bone = object.vertex_groups[group.group] 292 | 293 | if self.settings.prepend_armature: 294 | name = f'{armature.name}.{bone.name}' 295 | else: 296 | name = bone.name 297 | 298 | index = lookup[name] 299 | 300 | if index != -1: 301 | weight = group.weight 302 | self.bones.append([index, weight]) 303 | 304 | def to_string(self) -> str: 305 | parent = f'0' 306 | coords = ' '.join(f'{n:.6f}' for n in self.coords) 307 | normal = ' '.join(f'{n:.6f}' for n in self.normal) 308 | uvs = ' '.join(f'{n:.6f}' for n in self.uvs) 309 | count = f'{len(self.bones)}' 310 | bones = ' '.join(f'{i} {w:.6f}' for i, w in self.bones) 311 | 312 | if self.bones: 313 | return f'{parent} {coords} {normal} {uvs} {count} {bones}\n' 314 | else: 315 | return f'{parent} {coords} {normal} {uvs}\n' 316 | 317 | 318 | class Triangle: 319 | def __init__(self, settings: Settings): 320 | self.settings = settings 321 | self.material = '' 322 | self.vertices = [] 323 | 324 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object, mesh: bpy.types.Mesh, poly: bpy.types.MeshPolygon): 325 | if poly.material_index < len(mesh.materials): 326 | self.material = mesh.materials[poly.material_index] 327 | self.material = getattr(self.material, 'name', 'no_material') 328 | 329 | for loop in [mesh.loops[i] for i in poly.loop_indices]: 330 | vertex = Vertex(self.settings) 331 | vertex.from_blender(lookup, armature, object, mesh, loop) 332 | self.vertices.append(vertex) 333 | 334 | def to_string(self) -> str: 335 | material = f'{self.material}\n' 336 | vertices = ''.join(vertex.to_string() for vertex in self.vertices) 337 | return f'{material}{vertices}' 338 | 339 | 340 | class Triangles: 341 | def __init__(self, settings: Settings): 342 | self.settings = settings 343 | self.triangles = [] 344 | 345 | def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object): 346 | if object.type not in {'MESH', 'CURVE', 'SURFACE', 'FONT'}: 347 | return 348 | 349 | collection = bpy.data.collections.new('SourceOps') 350 | bpy.context.scene.collection.children.link(collection) 351 | object = object.copy() 352 | collection.objects.link(object) 353 | 354 | mod: bpy.types.TriangulateModifier = object.modifiers.new('Triangulate', 'TRIANGULATE') 355 | mod.min_vertices = 4 356 | mod.quad_method = 'FIXED' 357 | mod.ngon_method = 'CLIP' 358 | if hasattr(mod, 'keep_custom_normals'): 359 | mod.keep_custom_normals = True 360 | 361 | for mod in getattr(object, 'modifiers', []): 362 | if mod.type == 'ARMATURE': 363 | mod.show_viewport = False 364 | 365 | bpy.context.view_layer.update() 366 | depsgraph: bpy.types.Depsgraph = bpy.context.evaluated_depsgraph_get() 367 | evaluated: bpy.types.Object = object.evaluated_get(depsgraph) 368 | mesh = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) 369 | 370 | if not self.settings.ignore_transforms: 371 | mesh.transform(object.matrix_world) 372 | 373 | if hasattr(mesh, 'calc_normals_split'): 374 | mesh.calc_normals_split() 375 | 376 | for poly in mesh.polygons: 377 | triangle = Triangle(self.settings) 378 | triangle.from_blender(lookup, armature, object, mesh, poly) 379 | self.triangles.append(triangle) 380 | 381 | if hasattr(mesh, 'free_normals_split'): 382 | mesh.free_normals_split() 383 | 384 | bpy.data.meshes.remove(mesh) 385 | bpy.data.objects.remove(object) 386 | bpy.data.collections.remove(collection) 387 | 388 | def to_string(self) -> str: 389 | header = f'triangles\n' 390 | triangles = ''.join(triangle.to_string() for triangle in self.triangles) 391 | footer = f'end\n' 392 | return f'{header}{triangles}{footer}' 393 | 394 | 395 | class SMD: 396 | def __init__(self, prepend_armature: bool, ignore_transforms: bool): 397 | self.settings = Settings(prepend_armature, ignore_transforms) 398 | self.lookup = Lookup(self.settings) 399 | self.nodes = Nodes(self.settings) 400 | self.skeleton = Skeleton(self.settings) 401 | self.triangles = Triangles(self.settings) 402 | 403 | def configure_scene(self, objects: List[bpy.types.Object]) -> dict: 404 | scene_settings = {'objects': {o: {} for o in objects}} 405 | 406 | if bpy.context.active_object: 407 | scene_settings['mode'] = bpy.context.active_object.mode 408 | else: 409 | scene_settings['mode'] = 'OBJECT' 410 | 411 | if scene_settings['mode'] != 'OBJECT': 412 | bpy.ops.object.mode_set(mode='OBJECT') 413 | 414 | for object in objects: 415 | scene_settings['objects'][object]['hide_viewport'] = True if object.hide_viewport else False 416 | object.hide_viewport = False 417 | 418 | return scene_settings 419 | 420 | def restore_scene(self, scene_settings: dict): 421 | for object in scene_settings['objects'].keys(): 422 | object.hide_viewport = scene_settings['objects'][object]['hide_viewport'] 423 | 424 | if scene_settings['mode'] != 'OBJECT': 425 | bpy.ops.object.mode_set(mode=scene_settings['mode']) 426 | 427 | def from_blender(self, armature: bpy.types.Object, objects: List[bpy.types.Object], action: bpy.types.Action): 428 | if armature: 429 | all_objects = set([armature] + objects) 430 | else: 431 | all_objects = set(objects) 432 | 433 | scene_settings = self.configure_scene(all_objects) 434 | 435 | self.lookup.from_blender(armature) 436 | self.nodes.from_blender(self.lookup, armature) 437 | self.skeleton.from_blender(self.lookup, armature, action) 438 | 439 | for object in objects: 440 | self.triangles.from_blender(self.lookup, armature, object) 441 | 442 | self.restore_scene(scene_settings) 443 | 444 | def to_string(self) -> str: 445 | version = f'version 1\n' 446 | nodes = self.nodes.to_string() 447 | skeleton = self.skeleton.to_string() 448 | triangles = self.triangles.to_string() 449 | return f'{version}{nodes}{skeleton}{triangles}' 450 | -------------------------------------------------------------------------------- /addon/types/pyvmf/__init__.py: -------------------------------------------------------------------------------- 1 | from . import pyvmf 2 | -------------------------------------------------------------------------------- /addon/types/pyvmf/importer.py: -------------------------------------------------------------------------------- 1 | from . tools import num 2 | import re 3 | 4 | 5 | class TempCategory: 6 | """ 7 | Temporarily holds the VMF categories when reading the .VMF file 8 | 9 | :param category: The category name 10 | :type category: :obj:`str` 11 | :param indent: The level of indentation (how far nested inside other classes) 12 | :type indent: :obj:`int` 13 | """ 14 | 15 | # This class is used when reading the vmf file and when creating the vmf class later on 16 | def __init__(self, category, indent): 17 | self.category = category # versioninfo, visgroups, world, solid, dispinfo, etc... 18 | self.indent = indent 19 | self.data = [] # Everything inside the curly brackets other than child categories (ex: "skyname" "sky_dust") 20 | self.children = [] # List of all children categories (ex: side, dispinfo, editor, etc...) 21 | self.current_child = None # Used when going into nested children (ex: solid -> side -> dispinfo -> Normals) 22 | self.dic = {} # This is where all the data is stored when it's cleaned, used when creating VMF class 23 | 24 | def __repr__(self): 25 | return self.category 26 | 27 | def add_line(self, line, indent): 28 | """ 29 | :param line: The line of data to add to the current category 30 | :type line: :obj:`str` 31 | :param indent: The level of indentation (how far nested inside other classes) 32 | :type indent: :obj:`int` 33 | """ 34 | diff = indent - self.indent # Finding out how far into the nested children we need to go 35 | c = self 36 | for i in range(diff-1): 37 | c = c.current_child 38 | c.data.append(line) 39 | 40 | def add_child(self, category, indent): 41 | """ 42 | :param category: The category name 43 | :type category: :obj:`str` 44 | :param indent: The level of indentation (how far nested inside other classes) 45 | :type indent: :obj:`int` 46 | """ 47 | diff = indent - self.indent # Same concept as self.add_line 48 | c = self 49 | for i in range(diff-1): 50 | c = c.current_child 51 | 52 | new_child = TempCategory(category, indent) 53 | c.children.append(new_child) 54 | c.current_child = new_child 55 | 56 | def clean_up(self): 57 | """ 58 | Goes through all the data to remove unecessary characters 59 | """ 60 | self.category = self.category.split()[0] # We remove the tabs 61 | for i in self.data: 62 | clean = re.findall(r'\"(.*?)\"', i) # We remove the double quotes and separate (example line: "id" "2688") 63 | self.dic[clean[0]] = num(clean[1]) # The values, IF possible are turned into either ints or floats 64 | 65 | for j in self.children: 66 | j.clean_up() # Nested function calls 67 | 68 | 69 | def file_parser(file): 70 | """ 71 | Opens the file, extracts data line by line and turns it all into temporary categories 72 | 73 | :param file: The OS file to open, path needs to be included 74 | :type file: :obj:`str` 75 | :return: All the top level categories 76 | :rtype: :obj:`list` of :class:`TempCategory` 77 | """ 78 | with open(file, "r") as vmf: 79 | 80 | indent = 0 81 | previous_line = "versioninfo\n" # We only know it's a category the next line (the curly brackets open) 82 | extracted = [] 83 | 84 | for line in vmf.readlines()[1:]: 85 | if "}" in line: 86 | indent -= 1 87 | if indent == 0: # If indent is not 0 we know it's a child category and not a main category 88 | extracted.append(t) 89 | continue 90 | 91 | if "{" in line: 92 | if indent > 0: # If indent is not 0 we know it's a child category and not a main category 93 | # Open curly brackets ALWAYS follow a category, so we know the previous line is the category name 94 | t.add_child(previous_line, indent) 95 | else: 96 | t = TempCategory(previous_line, indent) # This is a main category (not a child category) 97 | indent += 1 98 | continue 99 | 100 | if "\"" in line: t.add_line(line, indent) # ALL lines with data have double quotes in them 101 | 102 | previous_line = line 103 | 104 | for c in extracted: 105 | # clean_up is a recursive function we only need to call it on the main categories 106 | c.clean_up() 107 | 108 | return extracted # This is used when creating a VMT class 109 | -------------------------------------------------------------------------------- /addon/types/pyvmf/tools.py: -------------------------------------------------------------------------------- 1 | def num(s: str): 2 | """ 3 | Tries to turn string into int or float 4 | 5 | :param s: The string to parse 6 | :type s: :obj:`str` 7 | :return: If unable to convert returns the input 8 | :rtype: :obj:`int` or :obj:`float` or :obj:`str` 9 | """ 10 | s = str(s) 11 | try: 12 | return int(s) 13 | except ValueError: 14 | try: 15 | return float(s) 16 | except ValueError: 17 | return str(s) 18 | -------------------------------------------------------------------------------- /addon/ui/__init__.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from . lists import SOURCEOPS_UL_GameList 3 | from . lists import SOURCEOPS_UL_ModelList 4 | from . lists import SOURCEOPS_UL_MaterialFolderList 5 | from . lists import SOURCEOPS_UL_SkinList 6 | from . lists import SOURCEOPS_UL_SequenceList 7 | from . lists import SOURCEOPS_UL_EventList 8 | from . lists import SOURCEOPS_UL_AttachmentList 9 | from . lists import SOURCEOPS_UL_ParticleList 10 | from . lists import SOURCEOPS_UL_MapList 11 | from . panels import SOURCEOPS_PT_MainPanel 12 | 13 | 14 | def register(): 15 | bpy.utils.register_class(SOURCEOPS_UL_GameList) 16 | bpy.utils.register_class(SOURCEOPS_UL_ModelList) 17 | bpy.utils.register_class(SOURCEOPS_UL_MaterialFolderList) 18 | bpy.utils.register_class(SOURCEOPS_UL_SkinList) 19 | bpy.utils.register_class(SOURCEOPS_UL_SequenceList) 20 | bpy.utils.register_class(SOURCEOPS_UL_EventList) 21 | bpy.utils.register_class(SOURCEOPS_UL_AttachmentList) 22 | bpy.utils.register_class(SOURCEOPS_UL_ParticleList) 23 | bpy.utils.register_class(SOURCEOPS_UL_MapList) 24 | bpy.utils.register_class(SOURCEOPS_PT_MainPanel) 25 | 26 | 27 | def unregister(): 28 | bpy.utils.unregister_class(SOURCEOPS_PT_MainPanel) 29 | bpy.utils.unregister_class(SOURCEOPS_UL_MapList) 30 | bpy.utils.unregister_class(SOURCEOPS_UL_AttachmentList) 31 | bpy.utils.unregister_class(SOURCEOPS_UL_ParticleList) 32 | bpy.utils.unregister_class(SOURCEOPS_UL_EventList) 33 | bpy.utils.unregister_class(SOURCEOPS_UL_SequenceList) 34 | bpy.utils.unregister_class(SOURCEOPS_UL_SkinList) 35 | bpy.utils.unregister_class(SOURCEOPS_UL_MaterialFolderList) 36 | bpy.utils.unregister_class(SOURCEOPS_UL_ModelList) 37 | bpy.utils.unregister_class(SOURCEOPS_UL_GameList) 38 | -------------------------------------------------------------------------------- /addon/ui/lists.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | 3 | 4 | class SOURCEOPS_UL_GameList(bpy.types.UIList): 5 | bl_idname = 'SOURCEOPS_UL_GameList' 6 | 7 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 8 | layout.prop(item, 'name', text='', emboss=False, translate=False) 9 | 10 | 11 | class SOURCEOPS_UL_ModelList(bpy.types.UIList): 12 | bl_idname = 'SOURCEOPS_UL_ModelList' 13 | 14 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 15 | layout.prop(item, 'name', text='', emboss=False, translate=False) 16 | 17 | 18 | class SOURCEOPS_UL_MaterialFolderList(bpy.types.UIList): 19 | bl_idname = 'SOURCEOPS_UL_MaterialFolderList' 20 | 21 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 22 | layout.prop(item, 'name', text='', emboss=False, translate=False) 23 | 24 | 25 | class SOURCEOPS_UL_SkinList(bpy.types.UIList): 26 | bl_idname = 'SOURCEOPS_UL_SkinList' 27 | 28 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 29 | layout.prop(item, 'name', text='', emboss=False, translate=False) 30 | 31 | 32 | class SOURCEOPS_UL_SequenceList(bpy.types.UIList): 33 | bl_idname = 'SOURCEOPS_UL_SequenceList' 34 | 35 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 36 | layout.prop(item, 'name', text='', emboss=False, translate=False) 37 | 38 | 39 | class SOURCEOPS_UL_EventList(bpy.types.UIList): 40 | bl_idname = 'SOURCEOPS_UL_EventList' 41 | 42 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 43 | layout.prop(item, 'name', text='', emboss=False, translate=False) 44 | 45 | 46 | class SOURCEOPS_UL_AttachmentList(bpy.types.UIList): 47 | bl_idname = 'SOURCEOPS_UL_AttachmentList' 48 | 49 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 50 | layout.prop(item, 'name', text='', emboss=False, translate=False) 51 | 52 | 53 | class SOURCEOPS_UL_ParticleList(bpy.types.UIList): 54 | bl_idname = 'SOURCEOPS_UL_ParticleList' 55 | 56 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 57 | layout.prop(item, 'name', text='', emboss=False, translate=False) 58 | 59 | 60 | class SOURCEOPS_UL_MapList(bpy.types.UIList): 61 | bl_idname = 'SOURCEOPS_UL_MapList' 62 | 63 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname): 64 | layout.prop(item, 'name', text='', emboss=False, translate=False) 65 | -------------------------------------------------------------------------------- /addon/ui/panels.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | from .. utils import common 3 | from .. import icons 4 | 5 | 6 | class SOURCEOPS_PT_MainPanel(bpy.types.Panel): 7 | bl_idname = 'SOURCEOPS_PT_MainPanel' 8 | bl_space_type = 'VIEW_3D' 9 | bl_region_type = 'UI' 10 | bl_category = 'SourceOps' 11 | bl_label = f'SourceOps - {common.get_version()}' 12 | 13 | def draw(self, context): 14 | layout = self.layout 15 | 16 | prefs = common.get_prefs(context) 17 | game = common.get_game(prefs) 18 | sourceops = common.get_globals(context) 19 | model = common.get_model(sourceops) 20 | material_folder = common.get_material_folder(model) 21 | skin = common.get_skin(model) 22 | sequence = common.get_sequence(model) 23 | event = common.get_event(sequence) 24 | attachment = common.get_attachment(model) 25 | particle = common.get_particle(model) 26 | map_props = common.get_map(sourceops) 27 | 28 | if sourceops: 29 | box = layout.box() 30 | row = box.row() 31 | row.scale_x = row.scale_y = 1.5 32 | row.label(text='Panel') 33 | row = row.row(align=True) 34 | row.alignment = 'RIGHT' 35 | row.prop(sourceops, 'panel', expand=True, icon_only=True) 36 | 37 | if prefs and sourceops.panel == 'GAMES': 38 | box = layout.box() 39 | row = box.row() 40 | row.alignment = 'CENTER' 41 | row.label(text='Games') 42 | 43 | row = box.row() 44 | row.template_list('SOURCEOPS_UL_GameList', '', prefs, 'game_items', prefs, 'game_index', rows=5) 45 | col = row.column(align=True) 46 | self.draw_list_buttons(col, 'GAMES') 47 | 48 | if game: 49 | col = common.split_column(box) 50 | col.prop(game, 'name') 51 | col.prop(game, 'game') 52 | col.prop(game, 'bin') 53 | col.prop(game, 'modelsrc') 54 | col.prop(game, 'models') 55 | col.prop(game, 'mapsrc') 56 | col.prop(game, 'mesh_type') 57 | 58 | elif sourceops and sourceops.panel == 'MODELS': 59 | box = layout.box() 60 | row = box.row() 61 | row.alignment = 'CENTER' 62 | row.label(text='Models') 63 | 64 | row = box.row() 65 | row.template_list('SOURCEOPS_UL_ModelList', '', sourceops, 'model_items', sourceops, 'model_index', rows=5) 66 | col = row.column(align=True) 67 | self.draw_list_buttons(col, 'MODELS') 68 | 69 | if model: 70 | col = common.split_column(box) 71 | col.prop(model, 'name') 72 | col.prop(model, 'armature') 73 | col.prop(model, 'reference') 74 | col.prop(model, 'collision') 75 | col.prop(model, 'bodygroups') 76 | col.prop(model, 'stacking') 77 | 78 | elif model and sourceops.panel == 'MODEL_OPTIONS': 79 | box = layout.box() 80 | row = box.row() 81 | row.alignment = 'CENTER' 82 | row.label(text='Model Options') 83 | 84 | col = common.split_column(box) 85 | col.prop(model, 'surface') 86 | col.prop(model, 'glass') 87 | col.prop(model, 'static') 88 | col.prop(model, 'rename_material') 89 | row = col.row() 90 | row.enabled = model.static 91 | row.prop(model, 'static_prop_combine') 92 | col.prop(model, 'joints') 93 | 94 | box = layout.box() 95 | row = box.row() 96 | row.alignment = 'CENTER' 97 | row.label(text='Transform Options') 98 | 99 | col = common.split_column(box) 100 | col.prop(model, 'prepend_armature') 101 | col.prop(model, 'ignore_transforms') 102 | 103 | sub = col.column() 104 | sub.enabled = not (model.static and model.static_prop_combine) 105 | sub.prop(model, 'origin_source') 106 | 107 | if model.origin_source == 'OBJECT': 108 | sub.prop(model, 'origin_object') 109 | 110 | else: 111 | align = sub.column(align=True) 112 | align.prop(model, 'origin_x', text='Origin X') 113 | align.prop(model, 'origin_y', text='Y') 114 | align.prop(model, 'origin_z', text='Z') 115 | 116 | sub.prop(model, 'rotation') 117 | 118 | col.prop(model, 'scale') 119 | 120 | elif model and sourceops.panel == 'TEXTURES': 121 | box = layout.box() 122 | row = box.row() 123 | row.alignment = 'CENTER' 124 | row.label(text='Material Folders') 125 | 126 | row = box.row() 127 | row.template_list('SOURCEOPS_UL_MaterialFolderList', '', model, 'material_folder_items', model, 'material_folder_index', rows=5) 128 | col = row.column(align=True) 129 | self.draw_list_buttons(col, 'MATERIAL_FOLDERS') 130 | 131 | if material_folder: 132 | col = common.split_column(box) 133 | col.prop(material_folder, 'name') 134 | 135 | box = layout.box() 136 | row = box.row() 137 | row.alignment = 'CENTER' 138 | row.label(text='Skins') 139 | 140 | row = box.row() 141 | row.template_list('SOURCEOPS_UL_SkinList', '', model, 'skin_items', model, 'skin_index', rows=5) 142 | col = row.column(align=True) 143 | self.draw_list_buttons(col, 'SKINS') 144 | 145 | if skin: 146 | col = common.split_column(box) 147 | col.prop(skin, 'name') 148 | 149 | elif model and sourceops.panel == 'SEQUENCES': 150 | box = layout.box() 151 | row = box.row() 152 | row.alignment = 'CENTER' 153 | row.label(text='Sequences') 154 | 155 | row = box.row() 156 | row.template_list('SOURCEOPS_UL_SequenceList', '', model, 'sequence_items', model, 'sequence_index', rows=5) 157 | col = row.column(align=True) 158 | self.draw_list_buttons(col, 'SEQUENCES') 159 | 160 | if sequence: 161 | col = common.split_column(box) 162 | col.prop(sequence, 'name') 163 | col.prop(sequence, 'action') 164 | 165 | col.prop(sequence, 'use_framerate') 166 | sub = col.column() 167 | sub.enabled = sequence.use_framerate 168 | sub.prop(sequence, 'framerate') 169 | 170 | col.prop(sequence, 'use_range') 171 | sub = col.column() 172 | sub.enabled = sequence.use_range 173 | sub.prop(sequence, 'start') 174 | sub.prop(sequence, 'end') 175 | 176 | col.prop(sequence, 'activity') 177 | col.prop(sequence, 'weight') 178 | col.prop(sequence, 'snap') 179 | col.prop(sequence, 'loop') 180 | 181 | elif sequence and sourceops.panel == 'EVENTS': 182 | box = layout.box() 183 | row = box.row() 184 | row.alignment = 'CENTER' 185 | row.label(text='Events') 186 | 187 | row = box.row() 188 | row.template_list('SOURCEOPS_UL_EventList', '', sequence, 'event_items', sequence, 'event_index', rows=5) 189 | col = row.column(align=True) 190 | self.draw_list_buttons(col, 'EVENTS') 191 | 192 | if event: 193 | col = common.split_column(box) 194 | col.prop(event, 'name') 195 | col.prop(event, 'event') 196 | col.prop(event, 'frame') 197 | col.prop(event, 'value') 198 | 199 | elif model and sourceops.panel == 'PARTICLES': 200 | box = layout.box() 201 | row = box.row() 202 | row.alignment = 'CENTER' 203 | row.label(text='Particles') 204 | 205 | row = box.row() 206 | row.template_list('SOURCEOPS_UL_ParticleList', '', model, 'particle_items', model, 'particle_index', rows=5) 207 | col = row.column(align=True) 208 | self.draw_list_buttons(col, 'PARTICLES') 209 | 210 | if particle: 211 | col = common.split_column(box) 212 | col.prop(particle, 'name') 213 | col.prop(particle, 'attachment_type') 214 | col.prop(particle, 'attachment_point') 215 | 216 | elif model and sourceops.panel == 'ATTACHMENTS': 217 | box = layout.box() 218 | row = box.row() 219 | row.alignment = 'CENTER' 220 | row.label(text='Attachments') 221 | 222 | row = box.row() 223 | row.template_list('SOURCEOPS_UL_AttachmentList', '', model, 'attachment_items', model, 'attachment_index', rows=5) 224 | col = row.column(align=True) 225 | self.draw_list_buttons(col, 'ATTACHMENTS') 226 | 227 | if attachment: 228 | col = common.split_column(box) 229 | col.prop(attachment, 'name') 230 | 231 | armature = model.armature 232 | if armature and armature.data: 233 | col.prop_search(attachment, 'bone', armature.data, 'bones') 234 | 235 | col.prop(attachment, 'offset') 236 | col.prop(attachment, 'rotation') 237 | col.prop(attachment, 'absolute') 238 | col.prop(attachment, 'rigid') 239 | 240 | if sourceops.panel in {'GAMES', 'MODELS', 'MODEL_OPTIONS', 'TEXTURES', 'SEQUENCES', 'EVENTS', 'ATTACHMENTS', 'PARTICLES'}: 241 | box = layout.box() 242 | row = box.row() 243 | row.scale_x = row.scale_y = 1.5 244 | row.label(text='Export') 245 | row = row.row(align=True) 246 | row.alignment = 'RIGHT' 247 | 248 | row.operator('sourceops.open_folder', text='', icon='FILEBROWSER') 249 | row.operator('sourceops.export_meshes', text='', icon_value=icons.id('smd')) 250 | row.operator('sourceops.generate_qc', text='', icon_value=icons.id('qc')) 251 | row.operator('sourceops.compile_qc', text='', icon_value=icons.id('mdl')) 252 | row.operator('sourceops.view_model', text='', icon_value=icons.id('hlmv')) 253 | row.operator('sourceops.export_auto', text='', icon='AUTO') 254 | 255 | if sourceops and sourceops.panel == 'MAPS': 256 | box = layout.box() 257 | row = box.row() 258 | row.alignment = 'CENTER' 259 | row.label(text='Maps') 260 | 261 | row = box.row() 262 | row.template_list('SOURCEOPS_UL_MapList', '', sourceops, 'map_items', sourceops, 'map_index', rows=5) 263 | col = row.column(align=True) 264 | self.draw_list_buttons(col, 'MAPS') 265 | 266 | if map_props: 267 | col = common.split_column(box) 268 | col.prop(map_props, 'name') 269 | col.prop(map_props, 'brush_collection') 270 | col.prop(map_props, 'disp_collection') 271 | col.prop(map_props, 'geometry_scale') 272 | col.prop(map_props, 'texture_scale') 273 | col.prop(map_props, 'lightmap_scale') 274 | col.prop(map_props, 'allow_skewed_textures') 275 | col.prop(map_props, 'align_to_grid') 276 | 277 | box = layout.box() 278 | row = box.row() 279 | row.scale_x = row.scale_y = 1.5 280 | row.label(text='Export') 281 | row = row.row(align=True) 282 | row.alignment = 'RIGHT' 283 | 284 | row.operator('sourceops.export_vmf', text='', icon_value=icons.id('vmf')) 285 | 286 | if sourceops and sourceops.panel == 'SIMULATION': 287 | box = layout.box() 288 | row = box.row() 289 | row.alignment = 'CENTER' 290 | row.label(text='Simulation') 291 | 292 | col = common.split_column(box) 293 | col.prop(sourceops, 'simulation_input') 294 | col.prop(sourceops, 'simulation_output') 295 | box.operator('sourceops.rig_simulation', text='Rig Simulation') 296 | 297 | if sourceops and sourceops.panel == 'MISC': 298 | box = layout.box() 299 | 300 | row = box.row() 301 | row.alignment = 'CENTER' 302 | row.label(text='Misc') 303 | 304 | col = box.column() 305 | col.operator('sourceops.weighted_normal') 306 | col.operator('sourceops.triangulate') 307 | col.operator('sourceops.pose_bone_transforms', text='Copy Pose Bone Translation').type = 'TRANSLATION' 308 | col.operator('sourceops.pose_bone_transforms', text='Copy Pose Bone Rotation').type = 'ROTATION' 309 | 310 | def draw_list_buttons(self, layout, item): 311 | op = layout.operator('sourceops.list_operator', text='', icon='ADD') 312 | op.mode, op.item = 'ADD', item 313 | op = layout.operator('sourceops.list_operator', text='', icon='REMOVE') 314 | op.mode, op.item = 'REMOVE', item 315 | 316 | layout.separator() 317 | op = layout.operator('sourceops.list_operator', text='', icon='DUPLICATE') 318 | op.mode, op.item = 'COPY', item 319 | layout.separator() 320 | 321 | op = layout.operator('sourceops.list_operator', text='', icon='TRIA_UP') 322 | op.mode, op.item = 'MOVE_UP', item 323 | op = layout.operator('sourceops.list_operator', text='', icon='TRIA_DOWN') 324 | op.mode, op.item = 'MOVE_DOWN', item 325 | -------------------------------------------------------------------------------- /addon/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from . import common 2 | from . import game 3 | from . import backup 4 | -------------------------------------------------------------------------------- /addon/utils/backup.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import json 3 | import pathlib 4 | from .. import utils 5 | 6 | 7 | def valid_keys(group): 8 | '''Yield valid keys for this property group, meaning everything except rna_type and bl_idname.''' 9 | for key in group.bl_rna.properties.keys(): 10 | if key not in {'rna_type', 'bl_idname'}: 11 | yield key 12 | 13 | 14 | def pref_prop(group, name): 15 | '''Call pref_prop_stored but without stored. Used for saving.''' 16 | pref, prop, stored = pref_prop_stored(group, None, name) 17 | return pref, prop 18 | 19 | 20 | def pref_prop_stored(group, storage, name): 21 | '''Get the the value and property of group[name], as well as the value from storage. Report the reason if it failed.''' 22 | pref = getattr(group, name, None) 23 | prop = group.bl_rna.properties.get(name) 24 | stored = storage.get(name) if storage else None 25 | 26 | if pref is None: 27 | print(f'SKIPPING {group}["{name}"] because it is NONE') 28 | 29 | elif prop.is_skip_save: 30 | print(f'SKIPPING {group}["{name}"] because it is SKIP SAVE') 31 | 32 | elif prop.is_readonly and prop.type not in {'POINTER', 'COLLECTION'}: 33 | print(f'SKIPPING {group}["{name}"] because it is READ ONLY') 34 | 35 | elif invalid_enum_item(group, storage, name, pref, prop, stored): 36 | print(f'SKIPPING {group}["{name}"] because it is INVALID ENUM ITEM') 37 | 38 | elif storage and stored is None: 39 | print(f'SKIPPING {group}["{name}"] because it is NOT STORED') 40 | 41 | else: 42 | return pref, prop, stored 43 | 44 | return None, None, None 45 | 46 | 47 | def invalid_enum_item(group, storage, name, pref, prop, stored): 48 | '''Check whether a value is valid for an enum by trying it and catching the exception.''' 49 | if prop.type == 'ENUM' and storage and stored not in {x.identifier for x in prop.enum_items}: 50 | try: 51 | if stored: 52 | setattr(group, name, stored) 53 | 54 | except: 55 | return True 56 | 57 | finally: 58 | if pref: 59 | setattr(group, name, pref) 60 | 61 | return False 62 | 63 | 64 | def save_recursive_group(group): 65 | '''Recursively save a property group.''' 66 | if group is not None: 67 | keys = valid_keys(group) 68 | storage = {k: save_recursive_by_name(group, k) for k in keys} 69 | return {k: v for k, v in storage.items() if v is not None} 70 | 71 | 72 | def save_recursive_by_name(group, name): 73 | '''Save an item from a property group.''' 74 | pref, prop = pref_prop(group, name) 75 | 76 | if pref is None: 77 | return None 78 | 79 | elif prop.type == 'POINTER': 80 | return save_recursive_group(pref) 81 | 82 | elif prop.type == 'COLLECTION': 83 | return [save_recursive_group(x) for x in pref] 84 | 85 | elif getattr(prop, 'is_array', None): 86 | return [x for x in pref] 87 | 88 | elif isinstance(pref, (bool, int, float, str)): 89 | return pref 90 | 91 | 92 | def load_recursive_group(group, storage): 93 | '''Recursively load a property group.''' 94 | for key in valid_keys(group): 95 | load_recursive_by_name(group, storage, key) 96 | 97 | 98 | def load_recursive_by_name(group, storage, name): 99 | '''Load an item from a property group.''' 100 | pref, prop, stored = pref_prop_stored(group, storage, name) 101 | 102 | if pref is None or stored is None: 103 | return 104 | 105 | elif prop.type == 'POINTER': 106 | load_recursive_group(pref, stored) 107 | 108 | elif prop.type == 'COLLECTION': 109 | try: 110 | while len(pref) < len(stored): 111 | pref.add() 112 | while len(pref) > len(stored): 113 | pref.remove(0) 114 | for a, b in zip(pref, stored): 115 | load_recursive_group(a, b) 116 | 117 | except Exception as exception: 118 | print(f'SKIPPING {group}["{name}"] because of EXCEPTION: {exception}') 119 | 120 | elif getattr(prop, 'is_array', None): 121 | try: 122 | indices = range(len(pref)) 123 | for index, value in zip(indices, stored): 124 | if pref[index] != value: 125 | pref[index] = value 126 | 127 | except Exception as exception: 128 | print(f'SKIPPING {group}["{name}"] because of EXCEPTION: {exception}') 129 | 130 | elif pref != stored: 131 | try: 132 | setattr(group, name, stored) 133 | 134 | except Exception as exception: 135 | print(f'SKIPPING {group}["{name}"] because of EXCEPTION: {exception}') 136 | 137 | 138 | def backup(path): 139 | '''Backup addon preferences to a file.''' 140 | prefs = utils.common.get_prefs(bpy.context) 141 | 142 | path = bpy.path.abspath(path) 143 | path = pathlib.Path(path).resolve() 144 | 145 | data = save_recursive_group(prefs) 146 | datastr = json.dumps(data, indent=1, sort_keys=False) 147 | 148 | try: 149 | path.write_text(datastr) 150 | except: 151 | return {'ERROR'}, f'Failed to open {path}', {'CANCELLED'} 152 | 153 | return {'INFO'}, f'Saved "{path}"', {'FINISHED'} 154 | 155 | 156 | def restore(path): 157 | '''Restore addon preferences from a file.''' 158 | prefs = utils.common.get_prefs(bpy.context) 159 | 160 | path = bpy.path.abspath(path) 161 | path = pathlib.Path(path).resolve() 162 | 163 | try: 164 | datastr = path.read_text() 165 | except: 166 | return {'ERROR'}, f'Failed to open {path}', {'CANCELLED'} 167 | 168 | data = json.loads(datastr) 169 | load_recursive_group(prefs, data) 170 | 171 | return {'INFO'}, f'Loaded "{path}"', {'FINISHED'} 172 | 173 | 174 | def filepath(): 175 | '''Get the default path to the preference backup file.''' 176 | user = bpy.utils.resource_path('USER') 177 | path = pathlib.Path(user).resolve() 178 | 179 | path = path.joinpath('scripts', 'presets', 'sourceops', 'prefs.json') 180 | path.parent.mkdir(parents=True, exist_ok=True) 181 | 182 | return str(path) 183 | -------------------------------------------------------------------------------- /addon/utils/common.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import string 3 | import unicodedata 4 | import platform 5 | import pathlib 6 | import traceback 7 | 8 | 9 | def get_version(): 10 | from ... import bl_info 11 | return '.'.join(str(n) for n in bl_info['version']) 12 | 13 | 14 | def get_prefs(context): 15 | addons = context.preferences.addons 16 | module = __name__.partition('.')[0] 17 | return addons[module].preferences 18 | 19 | 20 | def get_game(prefs): 21 | try: 22 | return prefs.game_items[prefs.game_index] 23 | except: 24 | return None 25 | 26 | 27 | def get_globals(context): 28 | try: 29 | return context.scene.sourceops 30 | except: 31 | return None 32 | 33 | 34 | def get_model(sourceops): 35 | try: 36 | return sourceops.model_items[sourceops.model_index] 37 | except: 38 | return None 39 | 40 | 41 | def get_material_folder(model): 42 | try: 43 | return model.material_folder_items[model.material_folder_index] 44 | except: 45 | return None 46 | 47 | 48 | def get_skin(model): 49 | try: 50 | return model.skin_items[model.skin_index] 51 | except: 52 | return None 53 | 54 | 55 | def get_sequence(model): 56 | try: 57 | return model.sequence_items[model.sequence_index] 58 | except: 59 | return None 60 | 61 | 62 | def get_event(sequence): 63 | try: 64 | return sequence.event_items[sequence.event_index] 65 | except: 66 | return None 67 | 68 | 69 | def get_attachment(model): 70 | try: 71 | return model.attachment_items[model.attachment_index] 72 | except: 73 | return None 74 | 75 | def get_particle(model): 76 | try: 77 | return model.particle_items[model.particle_index] 78 | except: 79 | return None 80 | 81 | def get_map(sourceops): 82 | try: 83 | return sourceops.map_items[sourceops.map_index] 84 | except: 85 | return None 86 | 87 | 88 | def split_column(layout): 89 | col = layout.column() 90 | col.use_property_split = True 91 | col.use_property_decorate = False 92 | return col 93 | 94 | 95 | filename_chars_valid = '-_.() %s%s' % (string.ascii_letters, string.digits) 96 | filename_chars_replace = ' ' 97 | filename_char_limit = 255 98 | 99 | 100 | def clean_filename(filename, whitelist=filename_chars_valid, replace=filename_chars_replace, char_limit=filename_char_limit): 101 | for r in replace: 102 | filename = filename.replace(r, '_') 103 | cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode() 104 | cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist) 105 | return cleaned_filename[:char_limit] 106 | 107 | 108 | def verify_folder(path): 109 | if not path.is_dir(): 110 | try: 111 | path.mkdir(parents=True, exist_ok=True) 112 | except: 113 | print(f'Failed to create directory: {path}') 114 | traceback.print_exc() 115 | return path 116 | 117 | 118 | def remove_duplicates(list_with_duplicates): 119 | return list(dict.fromkeys(list(list_with_duplicates))) 120 | 121 | 122 | def documents(): 123 | if platform.system() == 'Windows': 124 | import ctypes.wintypes 125 | buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) 126 | 127 | ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 1, buf) 128 | return pathlib.Path(buf.value) 129 | 130 | else: 131 | return pathlib.Path.home() 132 | 133 | 134 | def appdata(): 135 | user = bpy.utils.resource_path('USER') 136 | return pathlib.Path(user).resolve() 137 | 138 | 139 | def resolve(path): 140 | if path: 141 | return str(pathlib.Path(bpy.path.abspath(path)).resolve()) 142 | else: 143 | return '' 144 | 145 | 146 | def update_wine(self, context): 147 | self['wine'] = resolve(self.wine) 148 | -------------------------------------------------------------------------------- /addon/utils/game.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from ..utils.common import resolve 3 | 4 | 5 | def update_game(self, context): 6 | self['game'] = resolve(self.game) 7 | game = Path(self.game) 8 | 9 | if game.joinpath('gameinfo.txt').is_file(): 10 | bin = game.parent.joinpath('bin') 11 | 12 | if not bin.joinpath('studiomdl.exe').is_file(): 13 | for path in bin.iterdir(): 14 | if path.is_dir() and path.joinpath('studiomdl.exe').is_file(): 15 | bin = path 16 | break 17 | 18 | self['bin'] = str(bin) 19 | self['modelsrc'] = str(game.joinpath('modelsrc')) 20 | self['models'] = str(game.joinpath('models')) 21 | self['mapsrc'] = str(game.joinpath('mapsrc')) 22 | 23 | 24 | def update_bin(self, context): 25 | self['bin'] = resolve(self.bin) 26 | 27 | 28 | def update_modelsrc(self, context): 29 | self['modelsrc'] = resolve(self.modelsrc) 30 | 31 | 32 | def update_models(self, context): 33 | self['models'] = resolve(self.models) 34 | 35 | 36 | def update_mapsrc(self, context): 37 | self['mapsrc'] = resolve(self.mapsrc) 38 | 39 | 40 | def verify(game): 41 | gameinfo = Path(game.game).joinpath('gameinfo.txt') 42 | studiomdl = Path(game.bin).joinpath('studiomdl.exe') 43 | return gameinfo.is_file() and studiomdl.is_file() 44 | --------------------------------------------------------------------------------