├── LICENSE
├── README.md
├── __init__.py
├── bakelab_bake.py
├── bakelab_baked_data.py
├── bakelab_map.py
├── bakelab_post.py
├── bakelab_screen.png
├── bakelab_thumbnail_text_logo_small.jpg
├── bakelab_tools.py
├── bakelab_ui.py
└── bakelab_uv.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Blender-BakeLab2
2 | 
3 | BakeLab - A blender addon for baking images.
4 | Compatible with Blender 2.81 or higher.
5 | For blender version 2.79 go to [here](https://github.com/Shahzod114/Bakelab-Blender-addon)
6 |
7 | Main Features:
8 | * Automatically create images, setup materials, bake objects and save/pack images in one click;
9 | * Automatically generating materials;
10 | * Anti-Aliased baking;
11 | * Baking cycles displacement to real geometry;
12 | * Bake any PBR attributes of your material by its name (Metallic, Roughness, Specular and etc);
13 | * Adaptive image size by object's surface size;
14 | * Unwrap and Bake Multiple Objects into one image;
15 |
16 | video:
17 | https://youtu.be/XmXek3TPZLk
18 |
19 | 
20 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | # This program is free software; you can redistribute it and/or modify
2 | # it under the terms of the GNU General Public License as published by
3 | # the Free Software Foundation; either version 3 of the License, or
4 | # (at your option) any later version.
5 | #
6 | # This program is distributed in the hope that it will be useful, but
7 | # WITHOUT ANY WARRANTY; without even the implied warranty of
8 | # MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 | # General Public License for more details.
10 | #
11 | # You should have received a copy of the GNU General Public License
12 | # along with this program. If not, see .
13 |
14 | bl_info = {
15 | "name" : "BakeLab",
16 | "author" : "Shahzod Boyxonov (specoolar@gmail.com)",
17 | "description" : "Bake textures easily",
18 | "blender" : (2, 81, 0),
19 | "version" : (2, 0, 1),
20 | "location" : "View3D > Properties > BakeLab",
21 | "category" : "Baking"
22 | }
23 |
24 | if "bpy" in locals():
25 | import importlib
26 | importlib.reload(bakelab_bake)
27 | importlib.reload(bakelab_uv)
28 | importlib.reload(bakelab_baked_data)
29 | importlib.reload(bakelab_post)
30 | importlib.reload(bakelab_map)
31 | importlib.reload(bakelab_ui)
32 | else:
33 | from . import bakelab_bake
34 | from . import bakelab_uv
35 | from . import bakelab_baked_data
36 | from . import bakelab_post
37 | from . import bakelab_map
38 | from . import bakelab_ui
39 |
40 | import bpy
41 |
42 | from bpy.types import (
43 | Operator,
44 | PropertyGroup,
45 | Panel
46 | )
47 | from bpy.props import (
48 | IntProperty,
49 | EnumProperty,
50 | BoolProperty,
51 | FloatProperty,
52 | StringProperty,
53 | PointerProperty,
54 | CollectionProperty
55 | )
56 | from os.path import expanduser
57 |
58 | def updateAdaptiveImageMinSize(self, context):
59 | self.image_min_size = min(self.image_min_size, self.image_max_size)
60 |
61 | def updateAdaptiveImageMaxSize(self, context):
62 | self.image_max_size = max(self.image_min_size, self.image_max_size)
63 |
64 | def updateSavePath(self, context):
65 | if bpy.data.is_saved:
66 | self.save_path = bpy.path.abspath(self.save_path)
67 |
68 | class BakeLabProperties(PropertyGroup):
69 | bake_state: EnumProperty(
70 | items = (
71 | ("NONE", "None", ""),
72 | ("BAKING", "Baking", ""),
73 | ("BAKED", "Baked", "")
74 | ),
75 | default = "NONE"
76 | )
77 | bake_mode: EnumProperty(
78 | name = "Mode",
79 | description = 'Baking mode',
80 | items = (
81 | ("INDIVIDUAL", "Individual Objects", "", "PIVOT_INDIVIDUAL", 1),
82 | ("ALL_TO_ONE", "All To One Image", "", "PROP_ON", 2),
83 | ("TO_ACTIVE", "Selected to active", "", "PIVOT_ACTIVE", 3)
84 | ),
85 | default = "INDIVIDUAL"
86 | )
87 | cage_extrusion : FloatProperty(
88 | name = 'Cage Extrusion', default = 0.05,
89 | min = 0, soft_max = 1
90 | )
91 | pre_join_mesh : BoolProperty(
92 | name = 'Pre-Join Meshes', default = False,
93 | description = 'Create one merged mesh and bake to it using ray-tracing',
94 | )
95 | image_size : EnumProperty(
96 | name = 'Image Size',
97 | items = (
98 | ('FIXED', 'Fixed', "Fixed image size"),
99 | ('ADAPTIVE', 'Adaptive', "Image size by object's surface area")
100 | ),
101 | default = 'FIXED'
102 | )
103 | adaptive_image_Settings : BoolProperty(
104 | name = '',
105 | default = True
106 | )
107 | texel_per_unit : FloatProperty(
108 | name = 'Texels Per Unit',
109 | default = 100,
110 | min = 0
111 | )
112 | image_min_size : IntProperty(
113 | name = 'Min Size',
114 | default = 32,
115 | min = 1,
116 | update=updateAdaptiveImageMaxSize
117 | )
118 | image_max_size : IntProperty(
119 | name = 'Max Size',
120 | default = 2048,
121 | min = 1,
122 | update=updateAdaptiveImageMinSize
123 | )
124 | round_adaptive_image : BoolProperty(
125 | name = 'Round to power of two',
126 | default = True
127 | )
128 | anti_alias : IntProperty(
129 | name = 'Anti-aliasing', default = 1,
130 | description = 'Anti-aliasing (1 = No Anti-aliasing)',
131 | min = 1, soft_max = 8
132 | )
133 | bake_margin : IntProperty(
134 | name = 'Bake Margin',
135 | description = 'Extends the baked result as a post process filter',
136 | default = 4,
137 | min = 0,
138 | soft_max = 64
139 | )
140 | global_image_name : StringProperty(
141 | name = 'Image Name',
142 | description = 'Names of baked images',
143 | default = "Atlas",
144 | )
145 | compute_device : EnumProperty(
146 | name = 'Device',
147 | description = 'Compute Device',
148 | items = (
149 | ('GPU','GPU Compute',''),
150 | ('CPU','CPU','')
151 | )
152 | )
153 | save_or_pack : EnumProperty(
154 | name = 'Output',
155 | items = (
156 | ('PACK','Pack',''),
157 | ('SAVE','Save','')
158 | ),
159 | default = 'PACK'
160 | )
161 | create_folder : BoolProperty(
162 | name="Create folder",
163 | description="Automatically creates a folder named after the object(s)",
164 | default = True
165 | )
166 | folder_name : StringProperty(
167 | name = 'Folder name',
168 | description = 'Name of the folder',
169 | default = "Selection",
170 | )
171 | save_path : StringProperty(
172 | default=expanduser("~"),
173 | name="Folder",
174 | subtype="DIR_PATH",
175 | update=updateSavePath
176 | )
177 | show_bake_settings : BoolProperty(name = '', default = False)
178 | show_map_settings : BoolProperty(name = '', default = False)
179 | show_file_settings : BoolProperty(name = '', default = False)
180 |
181 | apply_only_selected : BoolProperty(
182 | name = 'Apply only to Selected',
183 | description = 'Apply only to selected objects',
184 | default = True
185 | )
186 | make_single_user : BoolProperty(
187 | name = 'Make single user',
188 | description = 'Make data single user',
189 | default = True
190 | )
191 | # Display
192 | baking_obj_count : IntProperty(
193 | name = 'Baking object count',
194 | default = 0
195 | )
196 | baking_obj_index : IntProperty(
197 | name = 'Current baking object',
198 | default = 0
199 | )
200 | baking_obj_name : StringProperty(
201 | name = 'Current baking object',
202 | default = ""
203 | )
204 | baking_map_count : IntProperty(
205 | name = 'Baking map count',
206 | default = 0
207 | )
208 | baking_map_index : IntProperty(
209 | name = 'Current baking map',
210 | default = 0
211 | )
212 | baking_map_type : StringProperty(
213 | name = 'Current baking map type',
214 | default = ""
215 | )
216 | baking_map_name : StringProperty(
217 | name = 'Current baking image',
218 | default = ""
219 | )
220 | baking_map_size : StringProperty(
221 | name = 'Current baking size',
222 | default = ""
223 | )
224 |
225 | classes = (
226 | BakeLabProperties,
227 |
228 | bakelab_bake.Baker,
229 | bakelab_uv.Unwrapper,
230 | bakelab_uv.ClearUV,
231 | bakelab_post.BakeLab_GenerateMaterials,
232 | bakelab_post.BakeLab_ApplyAO,
233 | bakelab_post.BakeLab_ApplyDisplace,
234 | bakelab_post.BakeLab_Finish,
235 | bakelab_map.BakeLabMap,
236 | bakelab_map.BakeLabAddMapItem,
237 | bakelab_map.BakeLabRemoveMapItem,
238 | bakelab_map.BakeLabMapListUI,
239 | bakelab_baked_data.BakeObjData,
240 | bakelab_baked_data.BakeMapData,
241 | bakelab_baked_data.BakeLab_BakedData,
242 | bakelab_map.BakeLabShowPassPresets,
243 | bakelab_ui.BakeLabUI
244 | )
245 |
246 | def register():
247 | for cls in classes:
248 | bpy.utils.register_class(cls)
249 |
250 | bpy.types.Scene.BakeLabProps = PointerProperty(type = BakeLabProperties)
251 | bpy.types.Scene.BakeLabMaps = CollectionProperty(type = bakelab_map.BakeLabMap)
252 | bpy.types.Scene.BakeLab_Data = CollectionProperty(type = bakelab_baked_data.BakeLab_BakedData)
253 | bpy.types.Scene.BakeLabMapIndex = IntProperty(name = 'BakeLab Map List Index')
254 |
255 | def unregister():
256 | for cls in classes:
257 | bpy.utils.unregister_class(cls)
258 |
259 | del bpy.types.Scene.BakeLabProps
260 | del bpy.types.Scene.BakeLabMaps
261 | del bpy.types.Scene.BakeLab_Data
262 | del bpy.types.Scene.BakeLabMapIndex
263 |
264 | if __name__ == "__main__":
265 | register()
266 |
--------------------------------------------------------------------------------
/bakelab_bake.py:
--------------------------------------------------------------------------------
1 | import os
2 | import bpy
3 |
4 | from bpy.types import (
5 | Operator,
6 | PropertyGroup,
7 | Panel
8 | )
9 | from bpy.props import (
10 | IntProperty,
11 | EnumProperty,
12 | BoolProperty,
13 | FloatProperty,
14 | StringProperty,
15 | PointerProperty,
16 | CollectionProperty
17 | )
18 |
19 | from math import log2
20 | from os.path import abspath, join, exists
21 |
22 | from .bakelab_tools import (
23 | SelectObject,
24 | SelectObjects,
25 | IsValidMesh
26 | )
27 |
28 | class Baker(Operator):
29 | """Bake"""
30 | bl_label = "BakeLab Bake"
31 | bl_info = "BakeLab"
32 | bl_idname = "bakelab.bake"
33 | bl_options = {'REGISTER', 'UNDO'}
34 |
35 | _timer = None
36 | TMP_EMPTY_MAT_NAME = "BAKELAB_TMP_EMPTY_MAT"
37 | TMP_IMAGE_NODE_NAME = "BAKELAB_TMP_IMAGE_NODE"
38 |
39 | def save_defaults(self, context):
40 | scene = context.scene
41 | render = scene.render
42 |
43 | # Image settings{
44 | img_settings = render.image_settings
45 | self.default_image_format = img_settings.file_format
46 | self.default_color_mode = img_settings.color_mode
47 | self.default_color_depth = img_settings.color_depth
48 |
49 | self.default_compression = img_settings.compression
50 | self.default_quality = img_settings.quality
51 | self.default_exr_codec = img_settings.exr_codec
52 | # }
53 |
54 | # Scene settings{
55 | self.default_active_object = context.active_object
56 | self.default_selected_objects = context.selected_objects
57 | self.default_engine = render.engine
58 | self.default_cycles_device = scene.cycles.device
59 | self.default_cycles_pause = scene.cycles.preview_pause
60 | # }
61 |
62 | # Bake settings{
63 | bake_settings = context.scene.render.bake
64 | self.default_use_s2a = bake_settings.use_selected_to_active
65 | self.default_use_clear = bake_settings.use_clear
66 | self.default_use_cage = bake_settings.use_cage
67 | self.default_cage_extrusion = bake_settings.cage_extrusion
68 | self.default_bake_margin = bake_settings.margin
69 | self.default_samples = scene.cycles.samples
70 | self.default_normal_space = bake_settings.normal_space
71 |
72 | self.default_use_pass_direct = bake_settings.use_pass_direct
73 | self.default_use_pass_indirect = bake_settings.use_pass_indirect
74 | self.default_use_pass_color = bake_settings.use_pass_color
75 |
76 | self.default_use_pass_diffuse = bake_settings.use_pass_diffuse
77 | self.default_use_pass_glossy = bake_settings.use_pass_glossy
78 | self.default_use_pass_trans = bake_settings.use_pass_transmission
79 | #self.default_use_pass_sss = bake_settings.use_pass_subsurface # No Longer in 2.83
80 | #self.default_use_pass_ao = bake_settings.use_pass_ambient_occlusion # No Longer in 3.0
81 | self.default_use_pass_emit = bake_settings.use_pass_emit
82 |
83 | self.default_use_cage = bake_settings.use_cage
84 | self.default_cage_extrusion = bake_settings.cage_extrusion
85 | self.default_cage_object = bake_settings.cage_object
86 | # }
87 |
88 | def restore_defaults(self, context):
89 | scene = context.scene
90 | render = scene.render
91 |
92 | # Image settings{
93 | img_settings = render.image_settings
94 | img_settings.file_format = self.default_image_format
95 | img_settings.color_mode = self.default_color_mode
96 | img_settings.color_depth = self.default_color_depth
97 |
98 | img_settings.compression = self.default_compression
99 | img_settings.quality = self.default_quality
100 | img_settings.exr_codec = self.default_exr_codec
101 | # }
102 |
103 | # Scene settings{
104 | SelectObjects(self.default_active_object, self.default_selected_objects)
105 | render.engine = self.default_engine
106 | scene.cycles.device = self.default_cycles_device
107 | scene.cycles.preview_pause = self.default_cycles_pause
108 | # }
109 |
110 | # Bake settings{
111 | bake_settings = context.scene.render.bake
112 | bake_settings.use_selected_to_active = self.default_use_s2a
113 | bake_settings.use_clear = self.default_use_clear
114 | bake_settings.use_cage = self.default_use_cage
115 | bake_settings.cage_extrusion = self.default_cage_extrusion
116 | bake_settings.margin = self.default_bake_margin
117 | scene.cycles.samples = self.default_samples
118 | bake_settings.normal_space = self.default_normal_space
119 |
120 | bake_settings.use_pass_direct = self.default_use_pass_direct
121 | bake_settings.use_pass_indirect = self.default_use_pass_indirect
122 | bake_settings.use_pass_color = self.default_use_pass_color
123 |
124 | bake_settings.use_pass_diffuse = self.default_use_pass_diffuse
125 | bake_settings.use_pass_glossy = self.default_use_pass_glossy
126 | bake_settings.use_pass_transmission = self.default_use_pass_trans
127 | #bake_settings.use_pass_subsurface = self.default_use_pass_sss # No Longer in 2.83
128 | #bake_settings.use_pass_ambient_occlusion = self.default_use_pass_ao # No Longer in 3.0
129 | bake_settings.use_pass_emit = self.default_use_pass_emit
130 |
131 | bake_settings.use_cage = self.default_use_cage
132 | bake_settings.cage_extrusion = self.default_cage_extrusion
133 | bake_settings.cage_object = self.default_cage_object
134 | # }
135 |
136 | def passes_to_rgb(self, node, src_socket, nodes, links, passes):
137 | has_bsdf_inputs = False
138 | for input in node.inputs:
139 | if input.type == 'SHADER':
140 | has_bsdf_inputs = True
141 | if len(input.links):
142 | self.passes_to_rgb(input.links[0].from_node, input,
143 | nodes, links, passes)
144 |
145 | if not has_bsdf_inputs:
146 | emit = nodes.new(type = 'ShaderNodeEmission')
147 | emit.inputs[0].default_value = 0, 0, 0, 0
148 | links.new(emit.outputs[0], src_socket)
149 | ####### Find Pass Input Socket{
150 | pass_input = None
151 | for Pass in passes:
152 | for tmp_input in node.inputs:
153 | if tmp_input.name.casefold() == Pass:
154 | pass_input = tmp_input
155 | break
156 | ####### }
157 | if pass_input:
158 | if len(pass_input.links):
159 | links.new(pass_input.links[0].from_socket, emit.inputs[0])
160 | else:
161 | if pass_input.type == 'RGBA':
162 | emit.inputs[0].default_value[0] = pass_input.default_value[0]
163 | emit.inputs[0].default_value[1] = pass_input.default_value[1]
164 | emit.inputs[0].default_value[2] = pass_input.default_value[2]
165 | emit.inputs[0].default_value[3] = pass_input.default_value[3]
166 | elif pass_input.type == 'VECTOR':
167 | emit.inputs[0].default_value[0] = pass_input.default_value[0]
168 | emit.inputs[0].default_value[1] = pass_input.default_value[1]
169 | emit.inputs[0].default_value[2] = pass_input.default_value[2]
170 | emit.inputs[0].default_value[3] = 1
171 | elif pass_input.type == 'VALUE':
172 | emit.inputs[0].default_value[0] = pass_input.default_value
173 | emit.inputs[0].default_value[1] = pass_input.default_value
174 | emit.inputs[0].default_value[2] = pass_input.default_value
175 | emit.inputs[0].default_value[3] = 1
176 |
177 | def passes_to_emit_node(self, mat, passes):
178 | nodes = mat.node_tree.nodes
179 | links = mat.node_tree.links
180 |
181 | out = self.find_node(nodes, 'OUTPUT_MATERIAL')
182 |
183 | if out:
184 | #### Modify Nodes
185 | split_passes = passes.split(',')
186 | for i in range(len(split_passes)):
187 | split_passes[i] = split_passes[i].strip().casefold()
188 | self.passes_to_rgb(out, None, nodes, links, split_passes)
189 | else:
190 | #### Create Default Texture Nodes
191 | out = nodes.new(type = 'ShaderNodeOutputMaterial')
192 | emit = nodes.new(type = 'ShaderNodeEmission')
193 | emit.inputs[0].default_value = 0, 0, 0, 0
194 | links.new(emit.outputs[0], out.inputs[0])
195 |
196 | def copy_node(self, dst_nodes, node):
197 | try:
198 | new_node = dst_nodes.new(type = node.bl_idname)
199 | except:
200 | return None
201 | for member in dir(node):
202 | try:
203 | value = getattr(node, member)
204 | if value is None:
205 | continue
206 | setattr(new_node, member, value)
207 | except:
208 | pass
209 | for src_input in node.inputs:
210 | dst_input = self.get_socket(new_node.inputs, src_input.identifier)
211 | if dst_input is not None:
212 | if hasattr(src_input, 'default_value') and \
213 | hasattr(dst_input, 'default_value'):
214 | dst_input.default_value = src_input.default_value
215 | return new_node
216 |
217 | def find_node(self, nodes, type):
218 | for node in nodes:
219 | if node.type == type:
220 | if type == "OUTPUT_MATERIAL":
221 | if node.is_active_output:
222 | return node
223 | else:
224 | return node
225 | return None
226 |
227 | def get_socket(self, sockets, identifier):
228 | for socket in sockets:
229 | if socket.identifier == identifier:
230 | return socket
231 | return None
232 |
233 | def extract_nodes_rc(
234 | self, gr_node, gr_in, gr_out,
235 | nodes, links, n_group, node_dict):
236 | if gr_node.name in node_dict:
237 | return node_dict[gr_node.name]
238 |
239 | node = self.copy_node(nodes, gr_node)
240 | node_dict[gr_node.name] = node
241 |
242 | if node is None:
243 | return None
244 |
245 | ### Inputs {
246 | for src_input in gr_node.inputs:
247 | dst_input = self.get_socket(node.inputs, src_input.identifier)
248 | if dst_input is None:
249 | continue
250 | for link in src_input.links:
251 | from_node = link.from_node
252 |
253 | if from_node == gr_in:
254 | ng_input = self.get_socket(n_group.inputs, link.from_socket.identifier)
255 | if ng_input is None:
256 | continue
257 | dst_input.default_value = ng_input.default_value
258 | for ng_link in ng_input.links:
259 | links.new(ng_link.from_socket, dst_input)
260 | else:
261 | link_node = self.extract_nodes_rc(
262 | from_node, gr_in, gr_out,
263 | nodes, links, n_group, node_dict)
264 | if link_node is not None:
265 | link_output = self.get_socket(link_node.outputs, link.from_socket.identifier)
266 | if link_output is not None:
267 | links.new(link_output, dst_input)
268 | ### }
269 | ### Outputs {
270 | for src_output in gr_node.outputs:
271 | dst_output = self.get_socket(node.outputs, src_output.identifier)
272 | if dst_output is None:
273 | continue
274 | for link in src_output.links:
275 | to_node = link.to_node
276 |
277 | if to_node == gr_out:
278 | ng_output = self.get_socket(n_group.outputs, link.to_socket.identifier)
279 | if ng_output is None:
280 | continue
281 | for ng_link in ng_output.links:
282 | links.new(dst_output, ng_link.to_socket)
283 | else:
284 | link_node = self.extract_nodes_rc(
285 | to_node, gr_in, gr_out,
286 | nodes, links, n_group, node_dict)
287 | if link_node is not None:
288 | link_input = self.get_socket(link_node.inputs, link.to_socket.identifier)
289 | if link_input is not None:
290 | links.new(dst_output, link_input)
291 | ### }
292 | return node
293 |
294 | def ungroup_nodes(self, node_tree):
295 | nodes = node_tree.nodes
296 | links = node_tree.links
297 | while True:
298 | group_exists = False
299 | ungroup_nodes = [n for n in nodes]
300 | for node in ungroup_nodes:
301 | if node.type != 'GROUP':
302 | continue
303 | group_exists = True
304 |
305 | node_dict = {}
306 | gr_nodes = node.node_tree.nodes
307 | gr_in = self.find_node(gr_nodes, 'GROUP_INPUT')
308 | gr_out = self.find_node(gr_nodes, 'GROUP_OUTPUT')
309 | if gr_in is None: continue
310 | if gr_out is None: continue
311 |
312 | for gr_node in gr_nodes:
313 | if gr_node == gr_in:
314 | continue
315 | if gr_node == gr_out:
316 | continue
317 | self.extract_nodes_rc(
318 | gr_node, gr_in, gr_out,
319 | nodes, links, node, node_dict)
320 | node_dict.clear()
321 | nodes.remove(node)
322 | if not group_exists:
323 | break
324 |
325 | def displacement_to_color(self, mat):
326 | nodes = mat.node_tree.nodes
327 | links = mat.node_tree.links
328 |
329 | out = self.find_node(nodes, 'OUTPUT_MATERIAL')
330 | if out == None:
331 | return
332 |
333 | if len(out.inputs[2].links) == 0:
334 | emit = nodes.new(type = 'ShaderNodeEmission')
335 | emit.inputs[0].default_value = 0, 0, 0, 0
336 | links.new(emit.outputs[0], out.inputs[0])
337 | else:
338 | from_socket = out.inputs[2].links[0].from_socket
339 | v_transform = nodes.new(type = 'ShaderNodeVectorTransform')
340 | links.remove(out.inputs[2].links[0])
341 |
342 | links.new(from_socket, v_transform.inputs[0])
343 | links.new(v_transform.outputs[0], out.inputs[0])
344 |
345 | def init_bake_settings(self, context, map):
346 | context.scene.cycles.samples = map.samples
347 | bake_settings = context.scene.render.bake
348 | bake_settings.normal_space = map.normal_space
349 |
350 | if map.type == 'Combined':
351 | bake_settings.use_pass_direct = map.combined_direct
352 | bake_settings.use_pass_indirect = map.combined_indirect
353 |
354 | bake_settings.use_pass_diffuse = map.combined_diffuse
355 | bake_settings.use_pass_glossy = map.combined_glossy
356 | bake_settings.use_pass_transmission = map.combined_transmission
357 | #bake_settings.use_pass_subsurface = map.combined_subsurface
358 | #bake_settings.use_pass_ambient_occlusion = map.combined_ambient_occlusion
359 | bake_settings.use_pass_emit = map.combined_emit
360 | else:
361 | bake_settings.use_pass_direct = map.bake_direct
362 | bake_settings.use_pass_indirect = map.bake_indirect
363 | bake_settings.use_pass_color = map.bake_color
364 |
365 | m_type = map.type
366 | if m_type == 'Albedo':
367 | bake_type = 'EMIT'
368 | if m_type == 'Combined':
369 | bake_type = 'COMBINED'
370 | if m_type == 'AO':
371 | bake_type = 'AO'
372 | if m_type == 'Displacement':
373 | bake_type = 'EMIT'
374 | if m_type == 'Shadow':
375 | bake_type = 'SHADOW'
376 | if m_type == 'Normal':
377 | bake_type = 'NORMAL'
378 | if m_type == 'UV':
379 | bake_type = 'UV'
380 | if m_type == 'Roughness':
381 | bake_type = 'ROUGHNESS'
382 | if m_type == 'Emission':
383 | bake_type = 'EMIT'
384 | if m_type == 'Environment':
385 | bake_type = 'ENVIRONMENT'
386 | if m_type == 'Diffuse':
387 | bake_type = 'DIFFUSE'
388 | if m_type == 'Glossy':
389 | bake_type = 'GLOSSY'
390 | if m_type == 'Subsurface':
391 | bake_type = 'Transmission'
392 | if m_type == 'CustomPass':
393 | bake_type = 'EMIT'
394 | return bake_type
395 |
396 | def calc_surf_area(self, obj):
397 | import bmesh
398 | bm = bmesh.new(use_operators=False)
399 | bm.from_mesh(obj.data)
400 | bm.transform(obj.matrix_world)
401 | bm.faces.ensure_lookup_table()
402 |
403 | area = 0.0
404 | for face in bm.faces:
405 | area += face.calc_area()
406 | return area
407 |
408 | def round_to_power_of_2(self, num):
409 | return pow(2,round(log2(num)))
410 |
411 | def PrepareImage(self, context, map, objs, name):
412 | props = context.scene.BakeLabProps
413 | self.SetSaveImageSettings(context, map)
414 |
415 | if props.image_size == 'FIXED':
416 | map.target_width = map.width
417 | map.target_height = map.height
418 | elif props.image_size == 'ADAPTIVE':
419 | area = 0
420 | for obj in objs:
421 | area += self.calc_surf_area(obj)
422 | size = pow(area, 0.5) * props.texel_per_unit
423 | if props.round_adaptive_image:
424 | size = self.round_to_power_of_2(size)
425 | map.target_width = size
426 | map.target_height = size
427 |
428 | map.final_aa = props.anti_alias
429 | if map.aa_override > 0:
430 | map.final_aa = map.aa_override
431 | bake_image = bpy.data.images.new(
432 | name = map.img_name.replace('*', name),
433 | width = map.target_width * map.final_aa,
434 | height = map.target_height * map.final_aa
435 | )
436 | bake_image.use_generated_float = map.float_depth
437 | try:
438 | bake_image.colorspace_settings.name = map.color_space
439 | except:
440 | try:
441 | if map.color_space == 'sRGB':
442 | bake_image.colorspace_settings.name = 'sRGB EOTF'
443 | elif map.color_space == 'Non-Color':
444 | bake_image.colorspace_settings.name = 'Non-Colour Data'
445 | except:
446 | self.report(type = {'WARNING'}, message = "Couldn't change color space of image")
447 |
448 | context.scene.render.bake.margin = props.bake_margin * map.final_aa
449 | if props.save_or_pack == 'PACK':
450 | bake_image.pack()
451 | else:
452 | extension = "."
453 | if map.file_format == 'PNG':
454 | extension = '.png'
455 | if map.file_format == 'JPEG':
456 | extension = '.jpg'
457 | if map.file_format == 'OPEN_EXR':
458 | extension = '.exr'
459 |
460 | abs_save_path = bpy.path.abspath(props.save_path)
461 | if not os.path.isdir(abs_save_path):
462 | os.makedirs(abs_save_path, 0o777)
463 |
464 | if props.create_folder:
465 | if props.bake_mode == "ALL_TO_ONE":
466 | bake_image.filepath = abspath(join(abs_save_path, props.folder_name, bake_image.name + extension))
467 | else:
468 | bake_image.filepath = abspath(join(abs_save_path, name, bake_image.name + extension))
469 | else:
470 | bake_image.filepath = abspath(join(abs_save_path, bake_image.name + extension))
471 |
472 | bake_image.save_render(bake_image.filepath)
473 |
474 | return bake_image
475 |
476 | def SetSaveImageSettings(self, context, map):
477 | img_settings = context.scene.render.image_settings
478 | img_settings.file_format = map.file_format
479 |
480 | if map.file_format == 'PNG':
481 | img_settings.color_mode = map.png_channels
482 | img_settings.color_depth = map.png_depth
483 | img_settings.compression = map.png_compression
484 | if map.file_format == 'JPEG':
485 | img_settings.color_mode = map.jpg_channels
486 | img_settings.quality = map.jpg_quality
487 | if map.file_format == 'OPEN_EXR':
488 | img_settings.color_mode = map.exr_channels
489 | img_settings.color_depth = map.exr_depth
490 | if map.exr_depth == '32':
491 | img_settings.exr_codec = map.exr_codec_32
492 | if map.exr_depth == '16':
493 | img_settings.exr_codec = map.exr_codec_16
494 |
495 | def ReserveMaterials(self, obj):
496 | selected_objects = bpy.context.selected_objects
497 | active_object = bpy.context.active_object
498 |
499 | SelectObject(obj)
500 | if len(obj.material_slots) == 0:
501 | bpy.ops.object.material_slot_add()
502 | for slot in obj.material_slots:
503 | self.object_slots.append(slot)
504 | self.original_materials.append(slot.material)
505 | if slot.material is not None:
506 | slot.material = slot.material.copy()
507 |
508 | SelectObjects(active_object,selected_objects)
509 |
510 | return (self.object_slots, self.original_materials)
511 |
512 | def RestoreMaterials(self):
513 | for i in range(0, min(len(self.object_slots), len(self.original_materials))):
514 | if self.object_slots[i] is not None:
515 | if self.object_slots[i].material is not None:
516 | bpy.data.materials.remove(self.object_slots[i].material)
517 | self.object_slots[i].material = self.original_materials[i]
518 | self.object_slots.clear()
519 | self.original_materials.clear()
520 |
521 | def PrepareMaterials(self, context, dst_obj, src_obj_list, map, bake_image):
522 | active_obj = context.active_object
523 | selected_objects = context.selected_objects
524 |
525 | for obj in src_obj_list:
526 | SelectObject(obj)
527 | if len(obj.material_slots) == 0:
528 | bpy.ops.object.material_slot_add()
529 | for slot in obj.material_slots:
530 | if slot.material is None:
531 | slot.material = self.GetEmptyMaterial()
532 | mat = slot.material
533 | mat.use_nodes = True
534 |
535 | if map.type == 'CustomPass':
536 | if map.deep_search:
537 | self.ungroup_nodes(mat.node_tree)
538 | self.passes_to_emit_node(mat, map.pass_name)
539 | if map.type == 'Albedo':
540 | self.ungroup_nodes(mat.node_tree)
541 | self.passes_to_emit_node(mat, 'Albedo,Color,Base Color,Col,Paint Color')
542 | if map.type == 'Displacement':
543 | self.displacement_to_color(mat)
544 |
545 | ###################
546 |
547 | SelectObject(dst_obj)
548 | if len(dst_obj.material_slots) == 0:
549 | bpy.ops.object.material_slot_add()
550 | for slot in dst_obj.material_slots:
551 | if slot.material is None:
552 | slot.material = self.GetEmptyMaterial()
553 | mat = slot.material
554 | mat.use_nodes = True
555 | if self.TMP_IMAGE_NODE_NAME in mat.node_tree.nodes:
556 | img_node = mat.node_tree.nodes[self.TMP_IMAGE_NODE_NAME]
557 | else:
558 | img_node = mat.node_tree.nodes.new(type = 'ShaderNodeTexImage')
559 | img_node.name = self.TMP_IMAGE_NODE_NAME
560 | mat.node_tree.nodes.active = img_node
561 | img_node.image = bake_image
562 |
563 | SelectObjects(active_obj, selected_objects)
564 |
565 | def GetEmptyMaterial(self):
566 | mat = bpy.data.materials.new(self.TMP_EMPTY_MAT_NAME)
567 | mat.use_nodes = True
568 | img_node = mat.node_tree.nodes.new(type = 'ShaderNodeTexImage')
569 | img_node.name = self.TMP_IMAGE_NODE_NAME
570 | return mat
571 |
572 | def create_merged_object(self, context, object_list):
573 | ##### Create New Object{
574 | merged_mesh = bpy.data.meshes.new('BAKELAB_MERGED_MESH_TMP')
575 | merged_obj = bpy.data.objects.new('BAKELAB_MERGED_OBJ_TMP', merged_mesh)
576 | merged_obj.location = 0, 0, 0
577 | context.scene.collection.objects.link(merged_obj)
578 | merged_mesh.update()
579 | ##### }
580 |
581 | for obj in object_list:
582 | SelectObject(obj)
583 | bpy.ops.object.duplicate(linked=False, mode='TRANSLATION')
584 | obj_clone = context.active_object
585 |
586 | #### Apply modifiers{
587 | for modifier in obj_clone.modifiers:
588 | if modifier.show_render:
589 | if modifier.type == 'SUBSURF':
590 | modifier.levels = modifier.render_levels
591 | bpy.ops.object.modifier_apply(modifier = modifier.name)
592 | ##### }
593 |
594 | #### Merge{
595 | SelectObject(merged_obj)
596 | obj_clone.select_set(True)
597 |
598 | clone_data = obj_clone.data
599 | bpy.ops.object.join()
600 | bpy.data.meshes.remove(clone_data)
601 | #### }
602 |
603 | while len(merged_obj.material_slots)>0:
604 | bpy.ops.object.material_slot_remove()
605 | merged_mesh.update()
606 | return merged_obj
607 |
608 | def down_scale(self, img, props, map):
609 | if map.final_aa == 1:
610 | return
611 | img.scale(map.target_width, map.target_height)
612 |
613 | def UpdateDisplayStatus(self, props, obj, map, image):
614 | props.baking_obj_name = obj.name
615 | if map.type == 'CustomPass':
616 | props.baking_map_type = map.pass_name + '(Custom Pass)'
617 | else:
618 | props.baking_map_type = map.type
619 | props.baking_map_name = image.name
620 | props.baking_map_size = str(map.target_width) + 'x' + str(map.target_height)
621 | if map.final_aa != 1:
622 | props.baking_map_size += str(' (' + str(map.final_aa)+'X)')
623 |
624 | def Bake(self, context):
625 | yield 1
626 | scene = context.scene
627 | render = scene.render
628 | props = scene.BakeLabProps
629 | self.original_materials = []
630 | self.object_slots = []
631 | self.save_defaults(context)
632 |
633 | props.bake_state = 'BAKING'
634 | scene.render.engine = 'CYCLES'
635 | scene.cycles.device = props.compute_device
636 | scene.cycles.preview_pause = True
637 | scene.render.bake.use_cage = True
638 | scene.render.bake.cage_extrusion = props.cage_extrusion
639 | scene.render.bake.cage_object = None
640 |
641 |
642 | if len(self.default_selected_objects) == 0:
643 | self.report(type = {'ERROR'}, message = 'Select some objects')
644 | yield -1
645 | selected_objects = [obj for obj in self.default_selected_objects if IsValidMesh(self, obj)]
646 | active_object = self.default_active_object
647 | if len(selected_objects) == 0:
648 | self.report(type = {'ERROR'}, message = 'No valid objects selected, see console for more info')
649 | yield -1
650 |
651 | if len(scene.BakeLabMaps) == 0:
652 | self.report(type = {'ERROR'}, message = 'Add bake maps')
653 | yield -1
654 |
655 | props.baking_map_index = 0
656 | props.baking_obj_index = 0
657 | props.baking_map_count = 0
658 | for map in scene.BakeLabMaps:
659 | if map.enabled:
660 | props.baking_map_count += 1
661 | props.baking_obj_count = len(selected_objects)
662 |
663 | ##########################################################################################
664 | if props.bake_mode == "INDIVIDUAL":
665 | for obj in selected_objects:
666 | if len(obj.data.uv_layers) == 0:
667 | self.report(type = {'ERROR'}, message = 'Not all objects have UV maps')
668 | yield -1
669 |
670 | render.bake.use_selected_to_active = False
671 |
672 | for obj in selected_objects:
673 | # Save baking data {
674 | baked_data = scene.BakeLab_Data.add()
675 | baked_data.AddObj(obj)
676 | # }
677 | props.baking_obj_index += 1
678 | SelectObject(obj)
679 | props.baking_map_index = 0
680 | for map in scene.BakeLabMaps:
681 | if not map.enabled:
682 | continue
683 | props.baking_map_index += 1
684 |
685 | self.ReserveMaterials(obj)
686 | bake_image = self.PrepareImage(context, map, {obj}, obj.name)
687 | self.PrepareMaterials(context, obj, {obj}, map, bake_image)
688 | bake_type = self.init_bake_settings(context, map)
689 |
690 | self.UpdateDisplayStatus(props,obj,map,bake_image)
691 |
692 | # Bake {
693 | while bpy.ops.object.bake('INVOKE_DEFAULT', type = bake_type) != {'RUNNING_MODAL'}:
694 | yield 1
695 | while not bake_image.is_dirty:
696 | yield 1
697 | # }
698 |
699 | self.down_scale(bake_image, props, map)
700 | if props.save_or_pack == 'PACK':
701 | bake_image.pack()
702 | else:
703 | bake_image.save_render(bake_image.filepath)
704 |
705 | baked_data.AddMap(map, bake_image) # Save baking data
706 | self.RestoreMaterials()
707 | ##########################################################################################
708 | elif props.bake_mode == "ALL_TO_ONE":
709 | # Check UVs {
710 | for obj in selected_objects:
711 | if len(obj.data.uv_layers) == 0:
712 | self.report(type = {'ERROR'}, message = 'Not all objects have UV maps')
713 | yield -1
714 | # }
715 |
716 | # Save baking data {
717 | baked_data = scene.BakeLab_Data.add()
718 | for obj in selected_objects:
719 | baked_data.AddObj(obj)
720 | # }
721 |
722 | if props.pre_join_mesh:
723 | render.bake.use_selected_to_active = True
724 | render.bake.use_cage = True
725 | render.bake.cage_extrusion = props.cage_extrusion
726 |
727 | merged_object = self.create_merged_object(context, selected_objects)
728 | SelectObjects(merged_object, selected_objects)
729 | else:
730 | render.bake.use_selected_to_active = False
731 |
732 | props.baking_map_index = 0
733 |
734 | for map in scene.BakeLabMaps:
735 | if not map.enabled:
736 | continue
737 | props.baking_map_index += 1
738 |
739 | if props.pre_join_mesh:
740 | for obj in selected_objects:
741 | self.ReserveMaterials(obj)
742 |
743 | bake_image = self.PrepareImage(context, map, {merged_object}, props.global_image_name)
744 | self.PrepareMaterials(context, merged_object, selected_objects, map, bake_image)
745 | bake_type = self.init_bake_settings(context, map)
746 |
747 | self.UpdateDisplayStatus(props,obj,map,bake_image)
748 |
749 | # Bake {
750 | while bpy.ops.object.bake('INVOKE_DEFAULT', type = bake_type) != {'RUNNING_MODAL'}:
751 | yield 1
752 | while not bake_image.is_dirty:
753 | yield 1
754 | # }
755 |
756 | self.RestoreMaterials()
757 |
758 | self.down_scale(bake_image, props, map)
759 | if props.save_or_pack == 'PACK':
760 | bake_image.pack()
761 | else:
762 | bake_image.save_render(bake_image.filepath)
763 | else:
764 | render.bake.use_clear = False
765 | bake_image = self.PrepareImage(context, map, selected_objects, props.global_image_name)
766 | for obj in selected_objects:
767 | SelectObject(obj)
768 | self.ReserveMaterials(obj)
769 |
770 | self.PrepareMaterials(context, obj, {obj}, map, bake_image)
771 | bake_type = self.init_bake_settings(context, map)
772 |
773 | self.UpdateDisplayStatus(props, obj, map, bake_image)
774 |
775 | # Bake {
776 | while bpy.ops.object.bake('INVOKE_DEFAULT', type = bake_type) != {'RUNNING_MODAL'}:
777 | yield 1
778 | while not bake_image.is_dirty:
779 | yield 1
780 | # }
781 |
782 | if props.save_or_pack == 'PACK':
783 | bake_image.pack()
784 | else:
785 | bake_image.save_render(bake_image.filepath)
786 |
787 | self.RestoreMaterials()
788 |
789 | self.down_scale(bake_image, props, map)
790 | if props.save_or_pack == 'PACK':
791 | bake_image.pack()
792 | else:
793 | bake_image.save_render(bake_image.filepath)
794 |
795 | baked_data.AddMap(map, bake_image) # Save baking data
796 |
797 | if props.pre_join_mesh:
798 | merged_data = merged_object.data
799 | bpy.data.objects.remove(merged_object)
800 | bpy.data.meshes.remove(merged_data)
801 | ##########################################################################################
802 | elif props.bake_mode == "TO_ACTIVE":
803 | if len(selected_objects) < 2:
804 | self.report(type = {'ERROR'}, message = 'Select atleast two mesh objects')
805 | yield -1
806 | if active_object.type != 'MESH':
807 | self.report(type = {'ERROR'}, message = 'Active object is not mesh type')
808 | yield -1
809 | if len(active_object.data.uv_layers) == 0:
810 | self.report(type = {'ERROR'}, message = 'Active object does not have UV maps')
811 | yield -1
812 |
813 | render.bake.use_selected_to_active = True
814 | render.bake.use_cage = True
815 | render.bake.cage_extrusion = props.cage_extrusion
816 |
817 | # Save baking data {
818 | baked_data = scene.BakeLab_Data.add()
819 | baked_data.AddObj(active_object)
820 | # }
821 |
822 | SelectObjects(active_object, selected_objects)
823 |
824 | props.baking_map_index = 0
825 |
826 | for map in scene.BakeLabMaps:
827 | if not map.enabled:
828 | continue
829 | props.baking_map_index += 1
830 |
831 | for obj in selected_objects:
832 | self.ReserveMaterials(obj)
833 |
834 | bake_image = self.PrepareImage(context, map, {active_object}, active_object.name)
835 | self.PrepareMaterials(
836 | context,
837 | active_object,
838 | [obj for obj in selected_objects
839 | if obj is not active_object],
840 | map,
841 | bake_image
842 | )
843 | bake_type = self.init_bake_settings(context, map)
844 |
845 | self.UpdateDisplayStatus(props,obj,map,bake_image)
846 |
847 | # Bake {
848 | while bpy.ops.object.bake('INVOKE_DEFAULT', type = bake_type) != {'RUNNING_MODAL'}:
849 | yield 1
850 | while not bake_image.is_dirty:
851 | yield 1
852 | # }
853 |
854 | self.down_scale(bake_image, props, map)
855 | if props.save_or_pack == 'PACK':
856 | bake_image.pack()
857 | else:
858 | bake_image.save_render(bake_image.filepath)
859 |
860 | baked_data.AddMap(map, bake_image) # Save baking data
861 | self.RestoreMaterials()
862 | ##########################################################################################
863 | props.bake_state = 'BAKED'
864 | yield 0 #Done
865 |
866 |
867 | def modal(self, context, event):
868 | if event.type in {'RIGHTMOUSE', 'ESC'}:
869 | self.cancel(context)
870 | return {'CANCELLED'}
871 |
872 | if event.type == 'TIMER':
873 | if context.scene.BakeLabProps.bake_state == 'BAKING':
874 | context.area.tag_redraw() # Update UI
875 | result = next(self.BakeCrt)
876 | if result == -1:
877 | self.cancel(context)
878 | return {'CANCELLED'}
879 | if result == 0:
880 | self.finish(context)
881 | return {'FINISHED'}
882 |
883 | return {'RUNNING_MODAL'}
884 |
885 | def cancel(self, context):
886 | context.scene.BakeLabProps.bake_state = 'NONE'
887 | self.finish(context)
888 |
889 | def finish(self, context):
890 | self.restore_defaults(context)
891 | if self.BakeCrt.gi_running:
892 | self.BakeCrt.close()
893 | wm = context.window_manager
894 | if self._timer:
895 | wm.event_timer_remove(self._timer)
896 |
897 | def execute(self, context):
898 | self.BakeCrt = self.Bake(context)
899 | wm = context.window_manager
900 | self._timer = wm.event_timer_add(0.5, window=context.window)
901 | wm.modal_handler_add(self)
902 | return {'RUNNING_MODAL'}
903 |
--------------------------------------------------------------------------------
/bakelab_baked_data.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from . import bakelab_map
3 |
4 | from bpy.types import (
5 | Operator,
6 | PropertyGroup,
7 | Panel
8 | )
9 | from bpy.props import (
10 | IntProperty,
11 | EnumProperty,
12 | BoolProperty,
13 | FloatProperty,
14 | StringProperty,
15 | PointerProperty,
16 | CollectionProperty
17 | )
18 | class BakeObjData(PropertyGroup):
19 | obj : PointerProperty(
20 | type=bpy.types.Object
21 | )
22 | class BakeMapData(PropertyGroup):
23 | bake_map : PointerProperty(
24 | type=bakelab_map.BakeLabMap
25 | )
26 | image : PointerProperty(
27 | type=bpy.types.Image
28 | )
29 |
30 | class BakeLab_BakedData(PropertyGroup):
31 | obj_list : CollectionProperty(
32 | type=BakeObjData
33 | )
34 | map_list : CollectionProperty(
35 | type=BakeMapData
36 | )
37 |
38 | def AddObj(self, obj):
39 | item = self.obj_list.add()
40 | item.obj = obj
41 |
42 | def AddMap(self, bake_map, image):
43 | item = self.map_list.add()
44 |
45 | item.bake_map.type = bake_map.type
46 | item.bake_map.pass_name = bake_map.pass_name
47 | item.bake_map.normal_space = bake_map.normal_space
48 |
49 | item.image = image
50 |
--------------------------------------------------------------------------------
/bakelab_map.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.types import (
3 | Operator,
4 | PropertyGroup,
5 | Panel
6 | )
7 | from bpy.props import (
8 | IntProperty,
9 | EnumProperty,
10 | BoolProperty,
11 | FloatProperty,
12 | StringProperty,
13 | PointerProperty,
14 | CollectionProperty
15 | )
16 |
17 | class BakeLabMap(PropertyGroup):
18 | enabled : BoolProperty(name = '', default = True)
19 | type : EnumProperty(
20 | name = 'Type',
21 | items = (
22 | ('Albedo', 'Albedo',''),
23 | ('Normal', 'Normal',''),
24 | ('Glossy', 'Glossy',''),
25 | ('Roughness', 'Roughness',''),
26 | ('Emission', 'Emission',''),
27 | ('Diffuse', 'Diffuse',''),
28 | ('Subsurface', 'Subsurface',''),
29 | ('Transmission','Transmission',''),
30 | ('Shadow', 'Shadow',''),
31 | ('Environment', 'Environment',''),
32 | ('UV', 'UV',''),
33 | None,
34 | ('Combined', 'Combined',''),
35 | ('CustomPass', 'Custom Pass',''),
36 | ('AO', 'Ambient Occlusion',''),
37 | ('Displacement','Displacement','')
38 | ),
39 | default = 'Albedo'
40 | )
41 | pass_name : StringProperty(name = 'Property name', default = 'Color,Base Color,Albedo,Paint Color')
42 | deep_search : BoolProperty(
43 | name = 'Deep Search',
44 | description = 'Search inside of node groups',
45 | default = True
46 | )
47 |
48 | img_name : StringProperty(name = 'Image name', default = '*')
49 | width : IntProperty(
50 | name = 'Width',
51 | default = 1024 ,
52 | min = 1, soft_max = 16384
53 | )
54 | height : IntProperty(
55 | name = 'Height',
56 | default = 1024,
57 | min = 1, soft_max = 16384
58 | )
59 | target_width : IntProperty(name = 'Target Width')
60 | target_height : IntProperty(name = 'Target Height')
61 | image_scale : FloatProperty(
62 | name = 'Image Scale',
63 | default = 1,
64 | min = 0
65 | )
66 | aa_override : IntProperty(
67 | name = 'Anti-alias Override',
68 | description = 'Use individual anti-aliasing (0 to use global value)',
69 | default = 0,
70 | min = 0, soft_max = 8
71 | )
72 | final_aa : IntProperty(name = 'Final Anti-alias')
73 |
74 |
75 | float_depth: BoolProperty(name = '32 bit float', default = False)
76 | color_space : EnumProperty(
77 | name = 'Color Space',
78 | description = 'Color Space',
79 | items = (('sRGB','sRGB',''),
80 | ('Non-Color','Non-Color','')),
81 | default = 'sRGB'
82 | )
83 | file_format : EnumProperty(
84 | name = 'Format',
85 | items = (
86 | ('PNG', 'PNG', ''),
87 | ('JPEG', 'JPEG', ''),
88 | ('OPEN_EXR', 'OpenEXR', '')
89 | )
90 | )
91 | png_channels : EnumProperty(
92 | name = 'Color',
93 | items = (('BW','BW',''),
94 | ('RGB','RGB',''),
95 | ('RGBA','RGBA','')),
96 | default = 'RGB'
97 | )
98 | png_depth : EnumProperty(
99 | name = 'Depth',
100 | description = 'Color Depth',
101 | items = (('8','8 byte',''),
102 | ('16','16 byte','')),
103 | default = '8'
104 | )
105 | png_compression : IntProperty(
106 | name = 'Compression',
107 | default = 15,
108 | description = 'Compression',
109 | min = 0, max = 100
110 | )
111 | jpg_channels : EnumProperty(
112 | name = 'Color',
113 | items = (('BW','BW',''),
114 | ('RGB','RGB','')),
115 | default = 'RGB'
116 | )
117 | jpg_quality : IntProperty(
118 | name = 'Quality',
119 | default = 90,
120 | description = 'Quality',
121 | min = 0, max = 100
122 | )
123 | exr_channels : EnumProperty(
124 | name = 'Color',
125 | items = (('RGB','RGB',''),
126 | ('RGBA','RGBA','')),
127 | default = 'RGB'
128 | )
129 | exr_depth : EnumProperty(
130 | name = 'Color Depth',
131 | description = 'Bits depth per channel',
132 | items = (('16', 'Half (16)',''),
133 | ('32', 'Full (32)','')),
134 | default = '32'
135 | )
136 | exr_codec_32 : EnumProperty(
137 | name = 'Codec',
138 | items = (
139 | ('NONE', 'None', ''),
140 | ('PXR24','Pxr24 (lossy)', ''),
141 | ('ZIP', 'ZIP (lossless)', ''),
142 | ('PIZ', 'PIZ (lossless)', ''),
143 | ('RLE', 'RLE (lossless)', ''),
144 | ('ZIPS', 'ZIPS (lossless)',''),
145 | ('DWAA', 'DWAA (lossy)', '')
146 | ),
147 | default = 'ZIP'
148 | )
149 | exr_codec_16 : EnumProperty(
150 | name = 'Codec',
151 | items = (
152 | ('NONE', 'None', ''),
153 | ('PXR24','Pxr24 (lossy)', ''),
154 | ('ZIP', 'ZIP (lossless)', ''),
155 | ('PIZ', 'PIZ (lossless)', ''),
156 | ('RLE', 'RLE (lossless)', ''),
157 | ('ZIPS', 'ZIPS (lossless)',''),
158 | ('B44', 'B44 (lossy)', ''),
159 | ('B44A', 'B44A (lossy)', ''),
160 | ('DWAA', 'DWAA (lossy)', '')
161 | ),
162 | default = 'ZIP'
163 | )
164 | samples : IntProperty(
165 | name = 'Samples',default = 6,
166 | description = 'Amount of Samples',
167 | min = 1, soft_max = 1024
168 | )
169 |
170 | normal_space : EnumProperty(
171 | name = 'Normal Space',
172 | items = (
173 | ('TANGENT','Tangent Space',''),
174 | ('OBJECT', 'Object Space','')
175 | )
176 | )
177 |
178 | bake_direct : BoolProperty(name = 'Direct', default = False)
179 | bake_indirect : BoolProperty(name = 'Indirect', default = False)
180 | bake_color : BoolProperty(name = 'Color', default = True)
181 |
182 | combined_direct : BoolProperty(name = 'Direct', default = True)
183 | combined_indirect : BoolProperty(name = 'Indirect', default = True)
184 |
185 | combined_diffuse : BoolProperty(name = 'Diffuse', default = True)
186 | combined_glossy : BoolProperty(name = 'Glossy', default = True)
187 | combined_transmission : BoolProperty(name = 'Transmission', default = True)
188 | #combined_subsurface : BoolProperty(name = 'Subsurface', default = True)
189 | #combined_ambient_occlusion : BoolProperty(name = 'AO', default = True)
190 | combined_emit : BoolProperty(name = 'Emit', default = True)
191 | ################################################################
192 | ################################################################
193 |
194 | class BakeLabAddMapItem(bpy.types.Operator):
195 | """Add a new bake map"""
196 | bl_idname = "bakelab.newmapitem"
197 | bl_label = "Add bake map"
198 | bl_options = {'REGISTER','UNDO'}
199 |
200 | type: EnumProperty(
201 | name = 'Type',
202 | items = (
203 | ('Albedo', 'Albedo',''),
204 | ('Normal', 'Normal',''),
205 | ('Glossy', 'Glossy',''),
206 | ('Roughness', 'Roughness',''),
207 | ('Emission', 'Emission',''),
208 | ('Diffuse', 'Diffuse',''),
209 | ('Subsurface', 'Subsurface',''),
210 | ('Transmission','Transmission',''),
211 | ('Shadow', 'Shadow',''),
212 | ('Environment', 'Environment',''),
213 | ('UV', 'UV',''),
214 | None,
215 | ('Combined', 'Combined',''),
216 | ('CustomPass', 'Custom Pass',''),
217 | ('AO', 'Ambient Occlusion',''),
218 | ('Displacement','Displacement','')
219 | ),
220 | default = 'Albedo'
221 | )
222 | width: IntProperty(name = 'Width',default = 1024,
223 | min = 1, soft_max = 16384)
224 | height: IntProperty(name = 'Height',default = 1024,
225 | min = 1, soft_max = 16384)
226 | image_scale: FloatProperty(name = 'Image Scale',default = 1,
227 | min = 0)
228 |
229 | float_depth: BoolProperty(name = '32 bit float', default = False)
230 | file_format : EnumProperty(
231 | name = 'Format',
232 | items = (
233 | ('PNG', 'PNG', ''),
234 | ('JPEG', 'JPEG', ''),
235 | ('OPEN_EXR', 'OpenEXR', '')
236 | )
237 | )
238 | png_channels : EnumProperty(
239 | name = 'Color',
240 | items = (('BW','BW',''),
241 | ('RGB','RGB',''),
242 | ('RGBA','RGBA','')),
243 | default = 'RGB'
244 | )
245 | png_depth : EnumProperty(
246 | name = 'Depth',
247 | description = 'Color Depth',
248 | items = (('8','8 byte',''),
249 | ('16','16 byte','')),
250 | default = '8'
251 | )
252 | png_compression : IntProperty(
253 | name = 'Compression',
254 | default = 15,
255 | description = 'Compression',
256 | min = 0, max = 100
257 | )
258 | jpg_channels : EnumProperty(
259 | name = 'Color',
260 | items = (('BW','BW',''),
261 | ('RGB','RGB','')),
262 | default = 'RGB'
263 | )
264 | jpg_quality : IntProperty(
265 | name = 'Quality',
266 | default = 90,
267 | description = 'Quality',
268 | min = 0, max = 100
269 | )
270 | exr_channels : EnumProperty(
271 | name = 'Color',
272 | items = (('RGB','RGB',''),
273 | ('RGBA','RGBA','')),
274 | default = 'RGB'
275 | )
276 | exr_depth : EnumProperty(
277 | name = 'Color Depth',
278 | description = 'Bits depth per channel',
279 | items = (('16', 'Half (16)',''),
280 | ('32', 'Full (32)','')),
281 | default = '32'
282 | )
283 | exr_codec_32 : EnumProperty(
284 | name = 'Codec',
285 | items = (
286 | ('NONE', 'None', ''),
287 | ('PXR24','Pxr24 (lossy)', ''),
288 | ('ZIP', 'ZIP (lossless)', ''),
289 | ('PIZ', 'PIZ (lossless)', ''),
290 | ('RLE', 'RLE (lossless)', ''),
291 | ('ZIPS', 'ZIPS (lossless)',''),
292 | ('DWAA', 'DWAA (lossy)', '')
293 | ),
294 | default = 'ZIP'
295 | )
296 | exr_codec_16 : EnumProperty(
297 | name = 'Codec',
298 | items = (
299 | ('NONE', 'None', ''),
300 | ('PXR24','Pxr24 (lossy)', ''),
301 | ('ZIP', 'ZIP (lossless)', ''),
302 | ('PIZ', 'PIZ (lossless)', ''),
303 | ('RLE', 'RLE (lossless)', ''),
304 | ('ZIPS', 'ZIPS (lossless)',''),
305 | ('B44', 'B44 (lossy)', ''),
306 | ('B44A', 'B44A (lossy)', ''),
307 | ('DWAA', 'DWAA (lossy)', '')
308 | ),
309 | default = 'ZIP'
310 | )
311 |
312 | def calcItemSettings(self,context,item):
313 | if self.type == 'Albedo':
314 | item.img_name = '*_t'
315 | item.samples = 4
316 | if self.type == 'Combined':
317 | item.img_name = '*_c'
318 | item.samples = 64
319 | if self.type == 'Normal':
320 | item.img_name = '*_n'
321 | item.samples = 16
322 | item.color_space = 'Non-Color'
323 | item.aa_override = 1 #Because cycles has buildin anti-aliasing for normals
324 | if self.type == 'Displacement':
325 | item.img_name = '*_h'
326 | item.samples = 4
327 | item.color_space = 'Non-Color'
328 | if self.type == 'AO':
329 | item.img_name = '*_ao'
330 | item.samples = 64
331 | item.color_space = 'Non-Color'
332 | if self.type == 'Shadow':
333 | item.img_name = '*_sh'
334 | item.samples = 32
335 | if self.type == 'Glossy':
336 | item.img_name = '*_s'
337 | item.samples = 8
338 | if self.type == 'Roughness':
339 | item.img_name = '*_r'
340 | item.samples = 4
341 | item.color_space = 'Non-Color'
342 | if self.type == 'Diffuse':
343 | item.img_name = '*_d'
344 | item.samples = 8
345 | if self.type == 'Emission':
346 | item.img_name = '*_e'
347 | item.samples = 4
348 | if self.type == 'Transmission':
349 | item.img_name = '*_a'
350 | item.samples = 8
351 | if self.type == 'UV':
352 | item.img_name = '*_uv'
353 | item.samples = 1
354 | if self.type == 'Environment':
355 | item.img_name = '*_env'
356 | item.samples = 16
357 | if self.type == 'Subsurface':
358 | item.img_name = '*_sss'
359 | item.samples = 64
360 | if self.type == 'CustomPass':
361 | item.img_name = '*_pass'
362 | item.samples = 4
363 | item.color_space = 'Non-Color'
364 |
365 | def draw(self,context):
366 | layout = self.layout
367 | props = context.scene.BakeLabProps
368 | layout.use_property_split = True
369 | layout.use_property_decorate = False
370 |
371 | layout.prop(self, "type")
372 | if props.image_size == 'FIXED':
373 | col = layout.column(align = True)
374 | col.prop(self, "width")
375 | col.prop(self, "height")
376 | elif props.image_size == 'ADAPTIVE':
377 | layout.prop(self, "image_scale")
378 |
379 | layout.prop(self, "float_depth")
380 | if props.save_or_pack == 'SAVE':
381 | row = layout.row()
382 | row.prop(self, "file_format")
383 |
384 | col = layout.column()
385 | if self.file_format == "PNG":
386 | row = col.row()
387 | row.prop(self, "png_channels", expand = True)
388 | row = col.row()
389 | row.prop(self, "png_depth", expand = True)
390 | col.prop(self, "png_compression")
391 | if self.file_format == "JPEG":
392 | row = col.row()
393 | row.prop(self, "jpg_channels", expand = True)
394 | col.prop(self, "jpg_quality")
395 | if self.file_format == "OPEN_EXR":
396 | row = col.row()
397 | row.prop(self, "exr_channels", expand = True)
398 | row = col.row()
399 | row.prop(self, "exr_depth", expand = True)
400 | if self.exr_depth == '32':
401 | col.prop(self, "exr_codec_32")
402 | if self.exr_depth == '16':
403 | col.prop(self, "exr_codec_16")
404 |
405 | def invoke(self, context, event):
406 | wm = context.window_manager
407 | return wm.invoke_props_dialog(self)
408 |
409 | def execute(self,context):
410 | context.area.tag_redraw()
411 | item = context.scene.BakeLabMaps.add()
412 |
413 | item.type = self.type
414 | item.width = self.width
415 | item.height = self.height
416 | item.image_scale = self.image_scale
417 |
418 | item.float_depth = self.float_depth
419 | item.file_format = self.file_format
420 | item.png_channels = self.png_channels
421 | item.png_depth = self.png_depth
422 | item.png_compression = self.png_compression
423 | item.jpg_channels = self.jpg_channels
424 | item.jpg_quality = self.jpg_quality
425 | item.exr_channels = self.exr_channels
426 | item.exr_depth = self.exr_depth
427 | item.exr_codec_32 = self.exr_codec_32
428 | item.exr_codec_16 = self.exr_codec_16
429 |
430 | self.calcItemSettings(context, item)
431 | context.scene.BakeLabMapIndex = len(context.scene.BakeLabMaps)-1
432 | return {'FINISHED'}
433 |
434 | class BakeLabRemoveMapItem(bpy.types.Operator):
435 | """Remove selected bake map"""
436 | bl_idname = "bakelab.removemapitem"
437 | bl_label = "remove bake map"
438 | bl_options = {'REGISTER','UNDO'}
439 |
440 | @classmethod
441 | def poll(cls,context):
442 | return context.scene.BakeLabMaps
443 |
444 | def execute(self,context):
445 | context.area.tag_redraw()
446 | context.scene.BakeLabMaps.remove(context.scene.BakeLabMapIndex)
447 | context.scene.BakeLabMapIndex = max(context.scene.BakeLabMapIndex - 1,0)
448 | context.scene.BakeLabMapIndex = min(context.scene.BakeLabMapIndex, len(context.scene.BakeLabMaps))
449 | return {'FINISHED'}
450 |
451 | class BakeLabShowPassPresets(Operator):
452 | """Show Presets"""
453 | bl_idname = "bakelab.show_pass_presets"
454 | bl_label = "BakeLab Show Pass Presets"
455 | pass_presets : EnumProperty(
456 | name = 'Pass Presets',
457 | items = (
458 | ('Color,Base Color,Albedo,Paint Color', 'Color/Albedo',''),
459 | ('Metallic', 'Metallic',''),
460 | ('Specular,Glossiness,Glossy', 'Specular',''),
461 | ('Roughness', 'Roughness',''),
462 | ('Anisotropic', 'Anisotropic',''),
463 | ('Sheen', 'Sheen',''),
464 | ('Clearcoat', 'Clearcoat',''),
465 | ('Transmission', 'Transmission ',''),
466 | ('Alpha', 'Alpha ','')
467 | )
468 | )
469 |
470 | def execute(self,context):
471 | context.area.tag_redraw()
472 | scene = context.scene
473 | if scene.BakeLabMapIndex>=0 and scene.BakeLabMaps:
474 | item = scene.BakeLabMaps[scene.BakeLabMapIndex]
475 | if item:
476 | item.pass_name = self.pass_presets
477 | return {'FINISHED'}
478 |
479 | ################################################################
480 |
481 | class BakeLabMapListUI(bpy.types.UIList):
482 | bl_idname = "BAKELAB_MAP_UL_list"
483 | def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
484 | if self.layout_type in {'DEFAULT', 'COMPACT'}:
485 | if item.type == 'CustomPass':
486 | layout.label(text = item.pass_name, icon = 'NONE')
487 | else:
488 | layout.label(text = item.type, icon = 'NONE')
489 | elif self.layout_type in {'GRID'}:
490 | layout.alignment = 'CENTER'
491 | layout.label(text = "", icon = 'TEXTURE')
492 | layout.prop(item, 'enabled')
493 |
--------------------------------------------------------------------------------
/bakelab_post.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.types import (
3 | Operator
4 | )
5 | from bpy.props import (
6 | IntProperty,
7 | EnumProperty,
8 | BoolProperty,
9 | FloatProperty,
10 | StringProperty,
11 | PointerProperty,
12 | CollectionProperty
13 | )
14 | from .bakelab_tools import (
15 | SelectObject,
16 | SelectObjects
17 | )
18 |
19 | class BakeLab_GenerateMaterials(Operator):
20 | """Generate materials based on baked datas"""
21 | bl_idname = "bakelab.generate_mats"
22 | bl_label = "Generate Materials"
23 | bl_options = {'REGISTER','UNDO'}
24 |
25 | def generate_mat(self, bakeMapData, name):
26 | new_mat = bpy.data.materials.new(name+'_BAKED')
27 | new_mat.use_nodes = True
28 | if self.add_nodes(bakeMapData, new_mat):
29 | return new_mat
30 | else:
31 | bpy.data.materials.remove(new_mat)
32 | return None
33 |
34 | def add_nodes(self, bakeMapData, mat):
35 | nodes = mat.node_tree.nodes
36 | links = mat.node_tree.links
37 | for node in nodes:
38 | nodes.remove(node)
39 |
40 | out = nodes.new(type = 'ShaderNodeOutputMaterial')
41 | out.location = 0, 0
42 | pbr = nodes.new(type = 'ShaderNodeBsdfPrincipled')
43 | pbr.location = -400, 0
44 | links.new(pbr.outputs[0],out.inputs[0])
45 | uvm = nodes.new(type = 'ShaderNodeTexCoord')
46 | uvm.location = -1800, 0
47 |
48 | pass_available = False
49 | node_y_shift = 0
50 | for data in bakeMapData:
51 | bake_map = data.bake_map
52 | bake_image = data.image
53 |
54 | if bake_map.type != 'CustomPass' and bake_map.type in self.baked_types:
55 | continue
56 | self.baked_types.append(bake_map.type)
57 |
58 | if bake_map.type == 'Albedo':
59 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
60 | imgNode.hide = True
61 | imgNode.location = -1000,-100
62 | imgNode.image = bake_image
63 | links.new(imgNode.outputs['Color'], pbr.inputs['Base Color'])
64 | links.new(uvm.outputs['UV'], imgNode.inputs['Vector'])
65 | pass_available = True
66 | if bake_map.type == 'Combined':
67 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
68 | imgNode.hide = True
69 | imgNode.location = -1000, 300
70 | imgNode.image = bake_image
71 | EmitNode = nodes.new(type = 'ShaderNodeEmission')
72 | EmitNode.location = -400, 300
73 | EmitNode.width = pbr.width
74 | EmitNode.hide = True
75 | links.new(imgNode.outputs['Color'], EmitNode.inputs[0])
76 | links.new(EmitNode.outputs[0], out.inputs[0])
77 | links.new(uvm.outputs['UV'], imgNode.inputs['Vector'])
78 | pass_available = True
79 | if bake_map.type == 'Normal':
80 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
81 | imgNode.hide = True
82 | imgNode.location = -1000, -500
83 | imgNode.image = bake_image
84 | nmNode = nodes.new(type = 'ShaderNodeNormalMap')
85 | nmNode.hide = True
86 | nmNode.location = -700, -500
87 | nmNode.space = bake_map.normal_space
88 | links.new(imgNode.outputs['Color'], nmNode.inputs['Color'])
89 | links.new(nmNode.outputs['Normal'], pbr.inputs['Normal'])
90 | links.new(uvm.outputs['UV'], imgNode.inputs['Vector'])
91 | pass_available = True
92 | if bake_map.type == 'AO':
93 | out.location[0] += 250
94 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
95 | imgNode.hide = True
96 | imgNode.location = -1000, 150
97 | imgNode.image = bake_image
98 | reroute = nodes.new(type = 'NodeReroute')
99 | reroute.location = -150, 150
100 | ao_mix = nodes.new(type = 'ShaderNodeMixShader')
101 | ao_mix.location = 0, 0
102 | ao_dark = nodes.new(type = 'ShaderNodeEmission')
103 | ao_dark.label = 'Dark'
104 | ao_dark.location = -400, 100
105 | ao_dark.width = pbr.width
106 | ao_dark.hide = True
107 | ao_dark.inputs[0].default_value = 0,0,0,0
108 | ao_dark.inputs[1].default_value = 0
109 |
110 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
111 | links.new(imgNode.outputs['Color'], reroute.inputs[0])
112 | links.new(reroute.outputs[0], ao_mix.inputs[0])
113 | links.new(ao_dark.outputs[0], ao_mix.inputs[1])
114 | links.new(pbr.outputs[0], ao_mix.inputs[2])
115 | links.new(ao_mix.outputs[0], out.inputs[0])
116 | pass_available = True
117 | if bake_map.type == 'Glossy':
118 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
119 | imgNode.hide = True
120 | imgNode.location = -1000, -200
121 | imgNode.image = bake_image
122 | links.new(imgNode.outputs['Color'],pbr.inputs['Specular IOR Level'])
123 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
124 | pass_available = True
125 | if bake_map.type == 'Roughness':
126 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
127 | imgNode.hide = True
128 | imgNode.location = -1000, -250
129 | imgNode.image = bake_image
130 | links.new(imgNode.outputs['Color'],pbr.inputs['Roughness'])
131 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
132 | pass_available = True
133 | if bake_map.type == 'Transmission':
134 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
135 | imgNode.hide = True
136 | imgNode.location = -1000, -900
137 | imgNode.image = bake_image
138 | links.new(imgNode.outputs['Color'],pbr.inputs['Transmission Weight'])
139 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
140 | pass_available = True
141 |
142 | ###### Custom Passes{
143 | if bake_map.type == 'CustomPass':
144 | ####### Find Pass Input Socket{
145 | split_passes = bake_map.pass_name.split(',')
146 | for i in range(len(split_passes)):
147 | split_passes[i] = split_passes[i].strip().casefold()
148 |
149 | pass_input = None
150 | for Pass in split_passes:
151 | for tmp_input in pbr.inputs:
152 | if tmp_input.name.casefold() == Pass:
153 | pass_input = tmp_input
154 | break
155 | # }
156 | if pass_input:
157 | if len(pass_input.links) == 0:
158 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
159 | imgNode.hide = True
160 | imgNode.location = -1400,node_y_shift
161 | imgNode.image = bake_image
162 | links.new(imgNode.outputs['Color'], pass_input)
163 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
164 | node_y_shift -= 100
165 | pass_available = True
166 | ####### }
167 | ###### }
168 | return pass_available
169 |
170 | def execute(self, context):
171 | props = context.scene.BakeLabProps
172 | active_obj = context.active_object
173 | selected_objects = context.selected_objects
174 | baked_data = context.scene.BakeLab_Data
175 |
176 | materials_created = False
177 | for data in baked_data:
178 | if data == None:
179 | continue
180 | self.baked_types = []
181 | name = context.scene.BakeLabProps.global_image_name
182 | if len(data.obj_list) == 1:
183 | if data.obj_list[0].obj != None:
184 | name = data.obj_list[0].obj.name
185 | if len(data.obj_list) == 0: # Just in case
186 | continue
187 |
188 | mat = self.generate_mat(data.map_list, name)
189 | if mat is None:
190 | continue
191 |
192 | materials_created = True
193 |
194 | for objData in data.obj_list:
195 | obj = objData.obj
196 | if obj == None:
197 | continue
198 |
199 | #if 'Normal' in self.baked_types:
200 | # obj.data.use_auto_smooth = False
201 |
202 | if props.apply_only_selected:
203 | if obj not in selected_objects:
204 | continue
205 |
206 | SelectObject(obj)
207 | if props.make_single_user:
208 | bpy.ops.object.make_single_user(object=True, obdata=True)
209 | if obj.data.uv_layers.active is not None:
210 | obj.data.uv_layers.active.active_render = True
211 | for slot in obj.material_slots:
212 | slot.material = mat
213 | SelectObjects(active_obj, selected_objects)
214 |
215 | if materials_created:
216 | return {'FINISHED'}
217 | else:
218 | self.report(type = {'ERROR'}, message = 'No valid baked images to create materials')
219 | return {'CANCELLED'}
220 |
221 | class BakeLab_ApplyAO(Operator):
222 | """Add ambient occlusion materials"""
223 | bl_idname = "bakelab.apply_ao"
224 | bl_label = "Apply AO"
225 | bl_options = {'REGISTER','UNDO'}
226 |
227 | def add_ao(self, bake_image, mat):
228 | nodes = mat.node_tree.nodes
229 | links = mat.node_tree.links
230 | out = None
231 | for node in nodes:
232 | if node.type == 'OUTPUT_MATERIAL':
233 | out = node
234 | break
235 | if out == None:
236 | return
237 |
238 | if len(out.inputs) == 0:
239 | return
240 | if len(out.inputs[0].links) == 0:
241 | return
242 | bsdf = out.inputs[0].links[0].from_node
243 |
244 |
245 | uvm = nodes.new(type = 'ShaderNodeTexCoord')
246 | uvm.hide = True
247 | uvm.width = bsdf.width
248 | uvm.location = bsdf.location[0], bsdf.location[1]+160
249 |
250 | imgNode = nodes.new(type = 'ShaderNodeTexImage')
251 | imgNode.hide = True
252 | imgNode.width = bsdf.width
253 | imgNode.location = bsdf.location[0], bsdf.location[1]+100
254 | imgNode.image = bake_image
255 |
256 | ao_mix = nodes.new(type = 'ShaderNodeMixShader')
257 | ao_mix.location = out.location[:]
258 | out.location[0] += 200
259 | ao_dark = nodes.new(type = 'ShaderNodeEmission')
260 | ao_dark.label = 'Dark'
261 | ao_dark.location = bsdf.location[0], bsdf.location[1]+50
262 | ao_dark.width = bsdf.width
263 | ao_dark.hide = True
264 | ao_dark.inputs[0].default_value = 0,0,0,0
265 | ao_dark.inputs[1].default_value = 0
266 |
267 | links.new(uvm.outputs['UV'],imgNode.inputs['Vector'])
268 | links.new(imgNode.outputs['Color'], ao_mix.inputs[0])
269 | links.new(ao_dark.outputs[0], ao_mix.inputs[1])
270 | links.new(bsdf.outputs[0], ao_mix.inputs[2])
271 | links.new(ao_mix.outputs[0], out.inputs[0])
272 |
273 | def execute(self, context):
274 | props = context.scene.BakeLabProps
275 | active_obj = context.active_object
276 | selected_objects = context.selected_objects
277 | baked_data = context.scene.BakeLab_Data
278 |
279 | materials_modified = False
280 | for data in baked_data:
281 | if data == None:
282 | continue
283 | for mapData in data.map_list:
284 | if mapData.bake_map == None:
285 | continue
286 | if mapData.bake_map.type != 'AO':
287 | continue
288 |
289 | for objData in data.obj_list:
290 | obj = objData.obj
291 | if obj == None:
292 | continue
293 | if props.apply_only_selected:
294 | if obj not in selected_objects:
295 | continue
296 |
297 | SelectObject(obj)
298 | if props.make_single_user:
299 | bpy.ops.object.make_single_user(object=True, obdata=True)
300 |
301 | if obj.data.uv_layers.active is not None:
302 | obj.data.uv_layers.active.active_render = True
303 |
304 | if len(obj.material_slots) == 0:
305 | bpy.ops.object.material_slot_add()
306 | for slot in obj.material_slots:
307 | if slot.material == None:
308 | slot.material = bpy.data.materials.new(obj.name+'_AO')
309 | slot.material.use_nodes = True
310 | if slot.material.users > 1:
311 | mat_name = slot.material.name
312 | slot.material = slot.material.copy()
313 | slot.material.name = mat_name + '_' + obj.name + '_AO'
314 | self.add_ao(mapData.image, slot.material)
315 | materials_modified = True
316 | break
317 |
318 | SelectObjects(active_obj, selected_objects)
319 | if materials_modified:
320 | return {'FINISHED'}
321 | else:
322 | self.report(type = {'ERROR'}, message = 'No valid baked images or objects to add AO')
323 | return {'CANCELLED'}
324 |
325 | class BakeLab_ApplyDisplace(Operator):
326 | """Apply material displacement as real geometry"""
327 | bl_idname = "bakelab.apply_displace"
328 | bl_label = "Apply Displacement"
329 | bl_options = {'REGISTER','UNDO'}
330 |
331 | def add_displacement(self, texture, obj):
332 | mod = obj.modifiers.new(name = 'Displacement', type = 'DISPLACE')
333 | mod.direction = 'RGB_TO_XYZ'
334 | mod.texture_coords = 'UV'
335 | mod.texture = texture
336 | mod.show_in_editmode = True
337 | mod.show_on_cage = True
338 |
339 | def execute(self, context):
340 | props = context.scene.BakeLabProps
341 | baked_data = context.scene.BakeLab_Data
342 | objects_modified = False
343 | for data in baked_data:
344 | if data == None:
345 | continue
346 | for mapData in data.map_list:
347 | if mapData.bake_map == None:
348 | continue
349 | if mapData.bake_map.type != 'Displacement':
350 | continue
351 |
352 | name = context.scene.BakeLabProps.global_image_name
353 | if len(data.obj_list) == 1:
354 | if data.obj_list[0].obj != None:
355 | name = data.obj_list[0].obj.name
356 | tex = bpy.data.textures.new(name = name, type = 'IMAGE')
357 | tex.intensity = 1.5
358 | tex.image = mapData.image
359 |
360 | for objData in data.obj_list:
361 | obj = objData.obj
362 | if obj == None:
363 | continue
364 | if props.apply_only_selected:
365 | if not obj.select_get():
366 | continue
367 |
368 | self.add_displacement(tex, obj)
369 | objects_modified = True
370 | break
371 |
372 | if objects_modified:
373 | return {'FINISHED'}
374 | else:
375 | self.report(type = {'ERROR'}, message = 'No valid baked images or objects to add Displacement')
376 | return {'CANCELLED'}
377 |
378 | class BakeLab_Finish(Operator):
379 | """Finish"""
380 | bl_label = "Finish"
381 | bl_idname = "bakelab.finish"
382 | bl_options = {'REGISTER', 'UNDO'}
383 |
384 | def execute(self, context):
385 | props = context.scene.BakeLabProps
386 | context.scene.BakeLab_Data.clear()
387 | props.bake_state = 'NONE'
388 | return {'FINISHED'}
389 |
--------------------------------------------------------------------------------
/bakelab_screen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/specoolar/Blender-BakeLab2/9917113a9c5a72e60847824cc55e2f6e83a08f15/bakelab_screen.png
--------------------------------------------------------------------------------
/bakelab_thumbnail_text_logo_small.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/specoolar/Blender-BakeLab2/9917113a9c5a72e60847824cc55e2f6e83a08f15/bakelab_thumbnail_text_logo_small.jpg
--------------------------------------------------------------------------------
/bakelab_tools.py:
--------------------------------------------------------------------------------
1 | import bpy
2 |
3 | def SelectObject(obj):
4 | bpy.ops.object.select_all(action = 'DESELECT')
5 | if obj:
6 | obj.select_set(True)
7 | bpy.context.view_layer.objects.active = obj
8 |
9 | def SelectObjects(active_obj, selected_objs):
10 | SelectObject(active_obj)
11 | for obj in selected_objs:
12 | if obj:
13 | obj.select_set(True)
14 |
15 | def IsValidMesh(self, obj):
16 | if obj.type != 'MESH':
17 | self.report(type = {'WARNING'}, message = 'Object ' + obj.name + ' is not mesh type')
18 | return False
19 | if len(obj.data.polygons) == 0:
20 | self.report(type = {'WARNING'}, message = 'Object ' + obj.name + ' has no faces')
21 | return False
22 | return True
--------------------------------------------------------------------------------
/bakelab_ui.py:
--------------------------------------------------------------------------------
1 | from bpy.types import (
2 | Panel
3 | )
4 |
5 | class BakeLabUI(Panel):
6 | bl_label = "BakeLab"
7 | bl_space_type = 'VIEW_3D'
8 | bl_idname = "BAKELAB_PT_ui"
9 | bl_region_type = 'UI'
10 | bl_context = "objectmode"
11 | bl_category = "BakeLab"
12 |
13 | def draw(self, context):
14 | scene = context.scene
15 | layout = self.layout
16 | layout.use_property_decorate = False
17 | props = scene.BakeLabProps
18 |
19 | if props.bake_state == 'NONE':
20 | col = layout.column()
21 | col.scale_y = 1.5
22 | col.operator("bakelab.bake", text = 'Bake', icon='RENDER_STILL')
23 |
24 | row = layout.row(align = True)
25 | row.operator("bakelab.unwrap", icon='UV')
26 | row.operator("bakelab.clear_uv", icon='UV')
27 |
28 | layout.separator()
29 |
30 | col = layout.column(align=True)
31 | col.label(text="Bake mode:")
32 | row = col.row(align = True)
33 | row.prop(props, "bake_mode", text='')
34 | row.prop(props, "show_bake_settings", icon = 'PREFERENCES')
35 | if props.show_bake_settings:
36 | box = col.box()
37 | col = box.column()
38 | col.use_property_split = True
39 | col.use_property_decorate = False
40 | col.prop(props, "bake_margin")
41 | if props.bake_mode == "TO_ACTIVE":
42 | col.prop(props, "cage_extrusion")
43 | if props.bake_mode == "ALL_TO_ONE":
44 | col.prop(props, "global_image_name")
45 | col.prop(props, "pre_join_mesh")
46 | if props.pre_join_mesh:
47 | col.prop(props, "cage_extrusion")
48 |
49 | layout.separator()
50 |
51 | layout.prop(props, "compute_device")
52 | col = layout.column(align=True)
53 | col.use_property_split = True
54 | col.use_property_decorate = False
55 | row = col.row(align=True)
56 | row.prop(props, "image_size")
57 | if props.image_size == 'ADAPTIVE':
58 | row.prop(props, "adaptive_image_Settings", icon='PREFERENCES')
59 | if props.adaptive_image_Settings:
60 | box = col.box()
61 | col = box.column()
62 | col.prop(props, "texel_per_unit")
63 | row = col.row(align = True)
64 | row.use_property_split = False
65 | row.prop(props, "image_min_size")
66 | row.prop(props, "image_max_size")
67 | col.prop(props, "round_adaptive_image")
68 |
69 | layout.use_property_split = True
70 | layout.prop(props, "anti_alias")
71 | layout.prop(props, "save_or_pack", expand=True)
72 | layout.use_property_split = False
73 | if props.save_or_pack == "SAVE":
74 | layout.prop(props, "save_path")
75 | layout.prop(props, "create_folder")
76 | if props.bake_mode == "ALL_TO_ONE":
77 | layout.prop(props, "folder_name")
78 | else:
79 | layout.label(text = "")
80 | col = layout.column()
81 | col.label(text = "Maps:")
82 | box = col.box()
83 | col = box.column(align = True)
84 | row = col.split(align = True)
85 | row.operator("bakelab.newmapitem", icon='ADD', text="")
86 | row.operator("bakelab.removemapitem", icon='REMOVE', text="")
87 |
88 | col.template_list("BAKELAB_MAP_UL_list", "", scene,
89 | "BakeLabMaps", scene, "BakeLabMapIndex", rows=2, maxrows=5)
90 |
91 | ##################################################
92 | if scene.BakeLabMapIndex >= 0 and scene.BakeLabMaps:
93 | item = scene.BakeLabMaps[scene.BakeLabMapIndex]
94 | col = col.column()
95 | col.use_property_split = True
96 | col.use_property_decorate = False
97 | col.enabled = item.enabled
98 | col.separator()
99 | subcol = col.column(align = True)
100 | row = subcol.row(align = True)
101 | row.prop(item, "type")
102 | row.prop(props, "show_map_settings", icon = 'PREFERENCES')
103 |
104 | if props.show_map_settings:
105 | box = subcol.box()
106 | scol = box.column()
107 | scol.prop(item, 'aa_override')
108 | if item.type != 'CustomPass':
109 | scol.prop(item, 'color_space')
110 | if item.type in {
111 | 'Combined',
112 | 'Diffuse',
113 | 'Glossy',
114 | 'Transmission',
115 | 'Subsurface',
116 | 'Normal'
117 | }:
118 | row = box.row()
119 | row.use_property_split = False
120 | if item.type == 'Combined':
121 | row = box.row(align = True)
122 | row.use_property_split = False
123 | row.prop(item, "combined_direct", toggle = True)
124 | row.prop(item, "combined_indirect", toggle = True)
125 |
126 | sub_box_col = box.column(align = True)
127 | sub_box_col.use_property_split = False
128 | row = sub_box_col.row(align = True)
129 | row.prop(item, "combined_diffuse", toggle = True)
130 | #row.prop(item, "combined_subsurface", toggle = True)
131 |
132 | row = sub_box_col.row(align = True)
133 | row.prop(item, "combined_glossy", toggle = True)
134 | #row.prop(item, "combined_ambient_occlusion", toggle = True)
135 |
136 | row = sub_box_col.row(align = True)
137 | row.prop(item, "combined_transmission", toggle = True)
138 | row.prop(item, "combined_emit", toggle = True)
139 |
140 | if item.type in {
141 | 'Diffuse',
142 | 'Glossy',
143 | 'Transmission',
144 | 'Subsurface'
145 | }:
146 | row = box.row(align = True)
147 | row.use_property_split = False
148 | row.prop(item, "bake_direct", toggle = True)
149 | row.prop(item, "bake_indirect", toggle = True)
150 | row.prop(item, "bake_color", toggle = True)
151 |
152 | if item.type == 'Normal':
153 | box.prop(item, "normal_space")
154 |
155 | subcol.separator()
156 |
157 | if item.type == 'CustomPass':
158 | col.label(text='Property Name')
159 | row = col.row(align = True)
160 | row.use_property_split = False
161 | row.prop(item, "pass_name", text='')
162 | row.operator_menu_enum(
163 | 'bakelab.show_pass_presets',
164 | 'pass_presets',
165 | icon = 'PRESET',
166 | text = ''
167 | )
168 | col.prop(item, 'color_space')
169 | col.prop(item, "deep_search")
170 |
171 | if item.type == 'Displacement':
172 | if not item.float_depth:
173 | col.label(text="Use 32 bit float type", icon = 'INFO')
174 | if props.save_or_pack == 'SAVE':
175 | if item.file_format != 'OPEN_EXR':
176 | col.label(text="Use EXR format", icon = 'INFO')
177 |
178 | col.separator()
179 |
180 | col.prop(item, "samples")
181 |
182 | col.separator()
183 | col.prop(item, "img_name")
184 |
185 | subcol = col.column(align = True)
186 | if props.image_size == 'FIXED':
187 | subcol.prop(item, "width")
188 | subcol.prop(item, "height")
189 | elif props.image_size == 'ADAPTIVE':
190 | subcol.prop(item, "image_scale")
191 |
192 | col.separator()
193 | col.prop(item, "float_depth")
194 | if props.save_or_pack == 'SAVE':
195 | row = col.row()
196 | row.prop(item, "file_format")
197 | row.prop(props, "show_file_settings", icon = 'PREFERENCES')
198 | if props.show_file_settings:
199 | subcol = col.column()
200 | if item.file_format == "PNG":
201 | row = subcol.row()
202 | row.prop(item, "png_channels", expand = True)
203 | row = subcol.row()
204 | row.prop(item, "png_depth", expand = True)
205 | subcol.prop(item, "png_compression")
206 | if item.file_format == "JPEG":
207 | row = subcol.row()
208 | row.prop(item, "jpg_channels", expand = True)
209 | subcol.prop(item, "jpg_quality")
210 | if item.file_format == "OPEN_EXR":
211 | row = subcol.row()
212 | row.prop(item, "exr_channels", expand = True)
213 | row = subcol.row()
214 | row.prop(item, "exr_depth", expand = True)
215 | if item.exr_depth == '32':
216 | subcol.prop(item, "exr_codec_32")
217 | if item.exr_depth == '16':
218 | subcol.prop(item, "exr_codec_16")
219 |
220 | else:
221 | if props.bake_state == 'BAKING':
222 | layout.label(text = 'Baking', icon = 'RENDER_STILL')
223 | if props.bake_mode == 'INDIVIDUAL':
224 | row = layout.row()
225 | row.label(text = 'Objects:')
226 | row.label(
227 | text =
228 | str(props.baking_obj_index) + ' of ' +
229 | str(props.baking_obj_count)
230 | )
231 | row = layout.row()
232 | row.label(text = 'Maps:')
233 | row.label(
234 | text =
235 | str(props.baking_map_index) + ' of ' +
236 | str(props.baking_map_count)
237 | )
238 |
239 | layout.separator()
240 |
241 | if props.bake_mode == 'INDIVIDUAL':
242 | row = layout.row()
243 | row.label(text = 'Current Object:')
244 | row.label(text = props.baking_obj_name)
245 |
246 | row = layout.row()
247 | row.label(text = 'Current Image:')
248 | row.label(text = props.baking_map_name)
249 | row = layout.row()
250 | row.label(text = '')
251 | row.label(text = props.baking_map_size)
252 |
253 | row = layout.row()
254 | row.label( text = 'Type:')
255 | row.label( text = props.baking_map_type)
256 | layout.template_running_jobs()
257 | elif props.bake_state == 'BAKED':
258 | layout.label(text = 'Baked', icon = 'CHECKMARK')
259 |
260 | if props.bake_mode == 'INDIVIDUAL':
261 | row = layout.row()
262 | row.label(text = 'Objects:')
263 | row.label(text = str(props.baking_obj_count))
264 |
265 | row = layout.row()
266 | row.label(text = 'Total images: ')
267 | if props.bake_mode == 'INDIVIDUAL':
268 | row.label(text = str(props.baking_map_count*props.baking_obj_count))
269 | else:
270 | row.label(text = str(props.baking_map_count))
271 |
272 | layout.separator()
273 |
274 | layout.prop(props, "apply_only_selected")
275 | layout.prop(props, "make_single_user")
276 | layout.operator("bakelab.generate_mats", icon='MATERIAL')
277 | layout.operator("bakelab.apply_ao", icon='SHADING_RENDERED')
278 | layout.operator("bakelab.apply_displace", icon='RNDCURVE')
279 | layout.separator()
280 | layout.operator("bakelab.finish")
281 |
--------------------------------------------------------------------------------
/bakelab_uv.py:
--------------------------------------------------------------------------------
1 | import bpy
2 | from bpy.types import (
3 | Operator
4 | )
5 | from bpy.props import (
6 | IntProperty,
7 | EnumProperty,
8 | BoolProperty,
9 | FloatProperty,
10 | StringProperty,
11 | PointerProperty,
12 | CollectionProperty
13 | )
14 | from .bakelab_tools import (
15 | SelectObject,
16 | SelectObjects,
17 | IsValidMesh
18 | )
19 |
20 | def SelectObject(obj):
21 | bpy.ops.object.select_all(action = 'DESELECT')
22 | obj.select_set(True)
23 | bpy.context.view_layer.objects.active = obj
24 |
25 | class Unwrapper(Operator):
26 | """Unwrap"""
27 | bl_idname = "bakelab.unwrap"
28 | bl_label = "Unwrap"
29 | bl_options = {'REGISTER','UNDO'}
30 |
31 | unwrap_method : EnumProperty(
32 | name = 'Unwrap Method',
33 | items = (
34 | ('smart_uv','Smart Project',''),
35 | ('lightmap_uv','LightMap Project','')
36 | ),
37 | default='smart_uv'
38 | )
39 | unwrap_mode : EnumProperty(
40 | name = 'Unwrap Mode',
41 | items = (
42 | ('INDIVIDUAL', 'All Individual', ''),
43 | ('ALL_TO_ONE', 'All Into One', ''),
44 | ('ONLY_ACTIVE', 'Only Active', '')
45 | )
46 | )
47 |
48 | smart_uv_angle : FloatProperty(
49 | name = 'Angle',
50 | description = 'Angle Limit',
51 | default = 66,
52 | min = 1,
53 | max = 89
54 | )
55 | smart_uv_margin : FloatProperty(
56 | name = 'Margin',
57 | description = 'Island Margin',
58 | default = 0.03,
59 | min = 0,
60 | max = 1
61 | )
62 |
63 | lightmap_quality : IntProperty(
64 | name = 'Quality',
65 | description = 'Pack Quality',
66 | default = 12,
67 | min = 1,
68 | max = 48
69 | )
70 | lightmap_margin : FloatProperty(
71 | name = 'Margin',
72 | description = 'Margin',
73 | default = 0.3,
74 | min = 0,
75 | max = 1
76 | )
77 |
78 | uvmap_options : EnumProperty(
79 | name = 'UVMaps',
80 | items = (
81 | ('CREATE_NEW', 'Create New',''),
82 | ('RE_UNWRAP', 'Unwrap active UV map','')
83 | ),
84 | default = 'CREATE_NEW'
85 | )
86 | uvmap_options_individual : EnumProperty(
87 | name = 'UVMaps',
88 | items = (
89 | ('CREATE_NEW', 'Create New', 'Create and Unwrap new UV Map'),
90 | ('IF_MISSING', 'Unwrap if missing', 'Create and Unwrap only if object has no UV Maps'),
91 | ('RE_UNWRAP', 'Unwrap active UV map', 'Unwrap existing UV maps (Create if does not exist)')
92 | ),
93 | default = 'CREATE_NEW'
94 | )
95 | default_uv_name : StringProperty(
96 | name = 'Default UV Name',
97 | description = 'New UV Layer name',
98 | default = 'BakeUVMap'
99 | )
100 | check_uv_name : BoolProperty(
101 | name = 'Check UV name',
102 | description = "Don't create new if object has UV with same name",
103 | default = True
104 | )
105 | apply_modifiers : BoolProperty(
106 | name = 'Apply Modifiers',
107 | default = True
108 | )
109 | make_single_user : BoolProperty(
110 | name = 'Make data single user',
111 | default = True
112 | )
113 | make_single_user_view : BoolProperty(
114 | name = 'Make data single user',
115 | default = True
116 | )
117 |
118 | def draw(self, context):
119 | layout = self.layout
120 | layout.use_property_split = True
121 | layout.use_property_decorate = False
122 |
123 | layout.prop(self, "unwrap_mode")
124 | if self.unwrap_mode == 'INDIVIDUAL':
125 | layout.prop(self, "uvmap_options_individual")
126 | layout.prop(self, "default_uv_name")
127 | if self.uvmap_options_individual == 'CREATE_NEW':
128 | layout.prop(self, "check_uv_name")
129 | else:
130 | layout.prop(self, "uvmap_options")
131 | layout.prop(self, "default_uv_name")
132 | if self.uvmap_options == 'CREATE_NEW':
133 | layout.prop(self, "check_uv_name")
134 |
135 | layout.prop(self, "apply_modifiers")
136 |
137 | lock_make_single_user = False
138 | if self.apply_modifiers:
139 | lock_make_single_user = True
140 | if self.unwrap_mode == 'ALL_TO_ONE':
141 | lock_make_single_user = True
142 |
143 | if lock_make_single_user:
144 | col = layout.column()
145 | col.enabled = False
146 | col.prop(self, "make_single_user_view")
147 | else:
148 | layout.prop(self, "make_single_user")
149 |
150 | layout.separator()
151 |
152 | layout.prop(self, "unwrap_method")
153 | if self.unwrap_method == 'smart_uv':
154 | layout.prop(self, "smart_uv_angle")
155 | layout.prop(self, "smart_uv_margin")
156 | if self.unwrap_method == 'lightmap_uv':
157 | layout.prop(self, "lightmap_quality")
158 | layout.prop(self, "lightmap_margin")
159 |
160 | def Unwrap(self, context):
161 | bpy.ops.object.mode_set(mode = 'EDIT')
162 | bpy.ops.mesh.select_all(action = 'SELECT')
163 |
164 | if self.unwrap_method == 'smart_uv':
165 | bpy.ops.uv.smart_project(
166 | angle_limit = self.smart_uv_angle / 57.2958, # To radian
167 | island_margin = self.smart_uv_margin
168 | )
169 | elif self.unwrap_method == 'lightmap_uv':
170 | bpy.ops.uv.lightmap_pack(
171 | PREF_BOX_DIV = self.lightmap_quality,
172 | PREF_MARGIN_DIV = self.lightmap_margin
173 | )
174 | bpy.ops.object.mode_set(mode = 'OBJECT')
175 |
176 | def modifier_apply(self, context, obj):
177 | active_object = context.active_object
178 | selected_objects = context.selected_objects
179 |
180 | SelectObject(obj)
181 | if obj.data.users > 1:
182 | bpy.ops.object.make_single_user(object=True,obdata=True)
183 |
184 | for modifier in obj.modifiers:
185 | if modifier.show_render:
186 | if modifier.type == 'SUBSURF':
187 | modifier.levels = modifier.render_levels
188 | bpy.ops.object.modifier_apply(modifier = modifier.name)
189 |
190 | SelectObjects(active_object, selected_objects)
191 |
192 | def execute(self,context):
193 | active_object = context.active_object
194 | selected_objects = context.selected_objects
195 | mesh_objects = [obj for obj in selected_objects if IsValidMesh(self, obj)]
196 | if len(mesh_objects) == 0:
197 | self.report(type = {'ERROR'}, message = 'No mesh objects selected')
198 | return {'CANCELLED'}
199 | ############################################################################
200 | if self.unwrap_mode == 'INDIVIDUAL':
201 | SelectObjects(mesh_objects[0], mesh_objects)
202 | if self.make_single_user:
203 | bpy.ops.object.make_single_user(object=True, obdata=True)
204 | unwrap_objects = mesh_objects
205 | else:
206 | unwrap_objects = []
207 | unwrap_datas = []
208 | for obj in mesh_objects:
209 | if obj.data in unwrap_datas:
210 | continue
211 | unwrap_objects.append(obj)
212 | unwrap_datas.append(obj.data)
213 |
214 | for obj in unwrap_objects:
215 | SelectObject(obj)
216 |
217 | if self.apply_modifiers:
218 | self.modifier_apply(context, obj)
219 |
220 | if self.uvmap_options_individual == 'CREATE_NEW':
221 | if self.check_uv_name and self.default_uv_name in obj.data.uv_layers:
222 | obj.data.uv_layers.active = obj.data.uv_layers[self.default_uv_name]
223 | else:
224 | obj.data.uv_layers.active = obj.data.uv_layers.new(name = self.default_uv_name)
225 | self.Unwrap(context)
226 | elif self.uvmap_options_individual == 'IF_MISSING':
227 | if len(obj.data.uv_layers) == 0:
228 | obj.data.uv_layers.new(name = self.default_uv_name)
229 | self.Unwrap(context)
230 | elif self.uvmap_options_individual == 'RE_UNWRAP':
231 | self.Unwrap(context)
232 |
233 |
234 | ############################################################################
235 | elif self.unwrap_mode == 'ONLY_ACTIVE':
236 | if active_object.type != 'MESH':
237 | self.report(type = {'ERROR'}, message = 'Active object is not mesh')
238 | SelectObjects(active_object, selected_objects)
239 | return {'CANCELLED'}
240 |
241 | SelectObject(active_object)
242 |
243 | if self.make_single_user:
244 | bpy.ops.object.make_single_user(object=True,obdata=True)
245 |
246 | if self.apply_modifiers:
247 | self.modifier_apply(context, active_object)
248 |
249 | if self.uvmap_options == 'CREATE_NEW':
250 | if self.check_uv_name and self.default_uv_name in active_object.data.uv_layers:
251 | active_object.data.uv_layers.active = active_object.data.uv_layers[self.default_uv_name]
252 | else:
253 | active_object.data.uv_layers.active = active_object.data.uv_layers.new(name = self.default_uv_name)
254 |
255 | self.Unwrap(context)
256 |
257 | ############################################################################
258 | elif self.unwrap_mode == 'ALL_TO_ONE':
259 | SelectObjects(mesh_objects[0], mesh_objects)
260 | bpy.ops.object.make_single_user(object=True, obdata=True)
261 |
262 | if self.uvmap_options == 'CREATE_NEW':
263 | for obj in mesh_objects:
264 | if self.apply_modifiers:
265 | self.modifier_apply(context, obj)
266 | if self.check_uv_name and self.default_uv_name in obj.data.uv_layers:
267 | obj.data.uv_layers.active = obj.data.uv_layers[self.default_uv_name]
268 | else:
269 | obj.data.uv_layers.active = obj.data.uv_layers.new(name = self.default_uv_name)
270 |
271 | self.Unwrap(context)
272 | ############################################################################
273 | SelectObjects(active_object, selected_objects)
274 | return {'FINISHED'}
275 |
276 | def invoke(self, context, event):
277 | props = context.scene.BakeLabProps
278 | if props.bake_mode == 'INDIVIDUAL':
279 | self.unwrap_mode = 'INDIVIDUAL'
280 | if props.bake_mode == 'ALL_TO_ONE':
281 | self.unwrap_mode = 'ALL_TO_ONE'
282 | if props.bake_mode == 'TO_ACTIVE':
283 | self.unwrap_mode = 'ONLY_ACTIVE'
284 | self.make_single_user_view = True
285 | wm = context.window_manager
286 | return wm.invoke_props_dialog(self)
287 |
288 | class ClearUV(Operator):
289 | """Clear UVs"""
290 | bl_idname = "bakelab.clear_uv"
291 | bl_label = "Clear UV"
292 | bl_options = {'REGISTER','UNDO'}
293 |
294 | save_active : BoolProperty(
295 | name = 'Save Active',
296 | default = True
297 | )
298 | save_active_render : BoolProperty(
299 | name = 'Save Active Render',
300 | default = True
301 | )
302 |
303 | def execute(self,context):
304 | mesh_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
305 | if len(mesh_objects) == 0:
306 | self.report(type = {'ERROR'}, message = 'No mesh objects selected')
307 | return {'CANCELLED'}
308 |
309 | for obj in mesh_objects:
310 | remove_uvs = []
311 | for uv in obj.data.uv_layers:
312 | if uv == obj.data.uv_layers.active and self.save_active:
313 | continue
314 | if uv.active_render and self.save_active_render:
315 | continue
316 | remove_uvs.append(uv)
317 | for uv in remove_uvs:
318 | obj.data.uv_layers.remove(uv)
319 |
320 | return {'FINISHED'}
321 |
322 | def invoke(self, context, event):
323 | wm = context.window_manager
324 | return wm.invoke_props_dialog(self)
325 |
--------------------------------------------------------------------------------