├── .gitattributes
├── .gitignore
├── ALT_CC0AssetDownloader.py
├── LICENSE
├── README.md
└── __init__.py
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | *.zip
3 | ambientCG_downloads_csv.csv
4 |
--------------------------------------------------------------------------------
/ALT_CC0AssetDownloader.py:
--------------------------------------------------------------------------------
1 | import csv
2 | import copy
3 | import zipfile
4 | import os
5 | import re
6 | import sys
7 | try:
8 | import requests
9 | except:
10 | import subprocess
11 | print('Module "requests" not found, attempting to install...')
12 | subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
13 | import requests
14 |
15 |
16 | # Converts the string "None" to Nonetype
17 | def strToNoneType(x):
18 | if x == 'None':
19 | x = None
20 | return x
21 |
22 |
23 | # Converts string "True"/"False" to actual boolean True/False values
24 | def strToBool(x):
25 | if x == 'True':
26 | return True
27 | if x == 'False':
28 | return False
29 |
30 |
31 | # Removes any items from the assets list that dont contain the specified keyword in assetId
32 | def filterByKeyword(assets, keyword):
33 | i = 0
34 | while i < len(assets):
35 | if keyword.upper() not in assets[i][0].upper():
36 | assets.pop(i)
37 | else:
38 | i+=1
39 | return assets
40 |
41 |
42 | # Removes any items from the assets list that dont have the specified attribute
43 | def filterByDownloadAttribute(assets, attribute):
44 | i = 0
45 | while i < len(assets):
46 | if assets[i][1] != attribute:
47 | assets.pop(i)
48 | else:
49 | i+=1
50 | return assets
51 |
52 |
53 | # Removes any items from the assets list that dont have the specified file extension
54 | def filterByFileExtension(assets, extension):
55 | i = 0
56 | while i < len(assets):
57 | if assets[i][2].upper() != extension.upper():
58 | assets.pop(i)
59 | else:
60 | i+=1
61 | return assets
62 |
63 |
64 | # Calls the above filtering functions if the inputs for those filters are not None
65 | def getAssetsByFilters(assets, assetfilters):
66 | assetsCopy = copy.deepcopy(assets) # Deepcopy to avoid modifying original assets list (Not really important to do this)
67 | if assetfilters[0] != None:
68 | assetsCopy = filterByKeyword(assetsCopy, assetfilters[0])
69 | if assetfilters[1] != None:
70 | assetsCopy = filterByDownloadAttribute(assetsCopy, assetfilters[1])
71 | if assetfilters[2] != None:
72 | assetsCopy = filterByFileExtension(assetsCopy, assetfilters[2])
73 | return assetsCopy
74 |
75 |
76 | def download(assets, saveLocation, unZip, deleteZips, skipDuplicates):
77 | print("Downloading...")
78 | for i in assets: # i = ['assetId', 'downloadAttribute', 'filetype', 'size', 'downloadLink', 'rawLink']
79 | fileExists = False
80 | if os.path.isdir(saveLocation+i[0]+'_'+i[1]):
81 | fileExists = True
82 | if os.path.isdir(saveLocation+i[0]+'_'+i[1]+'.'+i[2]):
83 | fileExists = True
84 |
85 | if (fileExists == False) or (skipDuplicates == False):
86 | try:
87 | print("Downloading {0}_{1} from {2}".format(i[0], i[1], i[4]))
88 | url = i[5]
89 | r = requests.get(url, allow_redirects=True)
90 | open(saveLocation+i[0]+'_'+i[1]+'.'+i[2], 'wb').write(r.content) #i [0]+'_'+i[1]+'.'+i[2] = assetID_downloadAttribute.extension
91 | except Exception as e:
92 | print("Failed to download {0}_{1} from {2}".format(i[0], i[1], i[4]))
93 | print(e)
94 | if i[2] == "zip" and unZip == True:
95 | try:
96 | print("Unzipping {0}_{1}.{2}".format(i[0],i[1],i[2]))
97 | with zipfile.ZipFile(saveLocation+i[0]+'_'+i[1]+'.'+i[2], 'r') as zip_ref:
98 | zip_ref.extractall(saveLocation+i[0]+'_'+i[1])
99 | if deleteZips == True:
100 | os.remove(saveLocation+i[0]+'_'+i[1]+'.'+i[2])
101 | except Exception as e:
102 | print("Failed to unzip {0}_{1}.{2}".format(i[0], i[1], i[2]))
103 | print(e)
104 | else:
105 | print("Skipping {0} since it already exists".format(saveLocation+i[0]+'_'+i[1]))
106 |
107 |
108 |
109 | yesInputs = ["y", "yes", "yes please"]
110 | noInputs = ["n", "no", "no thank you"]
111 |
112 |
113 | #AssetLibraryTools will do the input checking for this script, we just need to do some conversions
114 | print(sys.argv)
115 | saveLocation = sys.argv[1] + '/'
116 | keywordFilter = strToNoneType(sys.argv[2])
117 | attributeFilter = strToNoneType(sys.argv[3])
118 | extensionFilter = strToNoneType(sys.argv[4])
119 | unZip = strToBool(sys.argv[5])
120 | deleteZips = strToBool(sys.argv[6])
121 | skipDuplicates = strToBool(sys.argv[6])
122 |
123 |
124 | # Download asset data csv file
125 | # CSV file is formatted like this:
126 | #['assetId', 'downloadAttribute', 'filetype', 'size', 'downloadLink', 'rawLink']
127 | # For some reason it wont download the file unless you send a "User-Agent" header
128 | print("Downloading asset data from https://ambientcg.com/api/v2/downloads_csv\n")
129 | headers = {'User-Agent' : 'LJ3DSCRIPT'}
130 | url = 'https://ambientcg.com/api/v2/downloads_csv'
131 | r = requests.get(url, allow_redirects=True, headers=headers)
132 | filename = re.findall('filename=(.+)', r.headers.get('content-disposition'))[0]
133 | open(filename, 'wb').write(r.content) # Save downloaded file to disk
134 |
135 |
136 | # Open downloaded asset data csv file
137 | with open(filename, newline='') as f:
138 | reader = csv.reader(f)
139 | assets = list(reader)
140 | assets.pop(0) # Remove the 1st item since its not asset data, its column info
141 | print("Loaded csv file and found {0} assets\n".format(len(assets)))
142 |
143 |
144 | # Filter and sort the assets
145 | filteredAssets = getAssetsByFilters(assets, [keywordFilter, attributeFilter, extensionFilter])
146 | filteredAssets.sort()
147 |
148 |
149 | # Get the total size in bytes of the filtered assets
150 | filteredTotalSize = 0
151 | for i in filteredAssets:
152 | filteredTotalSize += int(i[3])
153 | print("=====\nFound {0} assets that match the filters, with a combined size of {1} bytes ({2} gigabytes)".format(len(filteredAssets), filteredTotalSize, filteredTotalSize/1e+9))
154 |
155 |
156 | print("=====\nDisplay asset names? (y/n)")
157 | while True:
158 | userInput = input()
159 | if userInput.lower() in yesInputs:
160 | for i in filteredAssets:
161 | print(i[0]+"_"+i[1])
162 | break
163 | if userInput in noInputs:
164 | break
165 | print("Invalid input")
166 |
167 |
168 | print("=====\nWould you like to download these assets? (y/n)")
169 | while True:
170 | userInput = input()
171 | if userInput.lower() in yesInputs:
172 | download(filteredAssets, saveLocation, unZip, deleteZips, skipDuplicates)
173 | break
174 | if userInput in noInputs:
175 | break
176 | print("Invalid input")
177 |
--------------------------------------------------------------------------------
/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 | # I WILL NOT BE MAINTAINING THIS ADDON ANYMORE.
2 |
3 | # AssetLibraryTools
4 |
5 | AssetLibraryTools is a free addon which aims to speed up the process of creating asset libraries with the asset browser, This addon is currently very much experimental as is the asset browser in blender.
6 |
7 | # Features
8 | * Batch import PBR materials from texture sets
9 | * Add real displacement to materials upon import
10 | * Add fake user to materials upon import
11 | * Skip materials that already exist
12 | * Import with UV or object mapping
13 | * Add extra utility nodes
14 | * Filter textures by string (dont load if contains x)
15 | * Batch import models of various filetypes (fbx, gltf, obj, x3d)
16 | * Hide imported models straight after import
17 | * Batch append objects/materials from multiple .blend files at once
18 | * Search for .blend files to append from in subdirs recursively
19 | * Dont append lights option
20 | * Dont append cameras option
21 | * Batch download CC0 assets from ambientcg.com via a python script
22 | * Filter assets by: Keyword, Download attributes, File extension
23 | * Unzip downloaded zip files automatically
24 | * Delete zip files after unzip automatically
25 | * Skip downloading files that already exist
26 | * Generate custom collection/object asset browser thumbnails (base code from https://github.com/johnnygizmo/asset_snapshot)
27 | * Batch import SBSAR files via Adobe substance 3D add-on for blender
28 | * Batch mark/unmark materials, meshes, objects, images, and textures as assets
29 | * Batch generate asset previews
30 | * Batch delete all materials/objects/textures/images/meshes
31 | * Enable real displacement for cycles on all materials at once
32 | * Change displacement scale on all materials at once
33 | * Clean up duplicate materials (based on name)
34 | * Clean up unused materials
35 | * And more to come
36 |
37 | 
38 |
39 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | bl_info = {
2 | "name": "AssetLibraryTools",
3 | "description": "AssetLibraryTools is a free addon which aims to speed up the process of creating asset libraries with the asset browser, This addon is currently very much experimental as is the asset browser in blender.",
4 | "author": "Lucian James (LJ3D)",
5 | "version": (0, 2, 2),
6 | "blender": (3, 0, 0),
7 | "location": "3D View > Tools",
8 | "warning": "Developed in 3.0, primarily the alpha. May be unstable or broken in future versions", # used for warning icon and text in addons panel
9 | "wiki_url": "https://github.com/LJ3D/AssetLibraryTools/wiki",
10 | "tracker_url": "https://github.com/LJ3D/AssetLibraryTools",
11 | "category": "3D View"
12 | }
13 |
14 | import bpy
15 | from bpy.props import (StringProperty,
16 | BoolProperty,
17 | IntProperty,
18 | FloatProperty,
19 | FloatVectorProperty,
20 | EnumProperty,
21 | PointerProperty,
22 | )
23 | from bpy.types import (Panel,
24 | Menu,
25 | Operator,
26 | PropertyGroup,
27 | )
28 | import pathlib
29 | import re
30 | import os
31 | import time
32 | import random
33 |
34 |
35 | # ------------------------------------------------------------------------
36 | # Stuff
37 | # ------------------------------------------------------------------------
38 |
39 | diffNames = ["diffuse", "diff", "albedo", "base", "col", "color"]
40 | sssNames = ["sss", "subsurface"]
41 | metNames = ["metallic", "metalness", "metal", "mtl", "met"]
42 | specNames = ["specularity", "specular", "spec", "spc"]
43 | roughNames = ["roughness", "rough", "rgh", "gloss", "glossy", "glossiness"]
44 | normNames = ["normal", "nor", "nrm", "nrml", "norm"]
45 | dispNames = ["displacement", "displace", "disp", "dsp", "height", "heightmap", "bump", "bmp"]
46 | alphaNames = ["alpha", "opacity"]
47 | emissiveNames = ["emissive", "emission"]
48 |
49 | nameLists = [diffNames, sssNames, metNames, specNames, roughNames, normNames, dispNames, alphaNames, emissiveNames]
50 | texTypes = ["diff", "sss", "met", "spec", "rough", "norm", "disp", "alpha", "emission"]
51 |
52 | # Find the type of PBR texture a file is based on its name
53 | def FindPBRTextureType(fname):
54 | PBRTT = None
55 | # Remove digits
56 | fname = ''.join(i for i in fname if not i.isdigit())
57 | # Separate CamelCase by space
58 | fname = re.sub("([a-z])([A-Z])","\g<1> \g<2>",fname)
59 | # Replace common separators with SPACE
60 | seperators = ['_', '.', '-', '__', '--', '#']
61 | for sep in seperators:
62 | fname = fname.replace(sep, ' ')
63 | # Set entire string to lower case
64 | fname = fname.lower()
65 | # Find PBRTT
66 | i = 0
67 | for nameList in nameLists:
68 | for name in nameList:
69 | if name in fname:
70 | PBRTT = texTypes[i]
71 | i+=1
72 | return PBRTT
73 |
74 |
75 | # Display a message in the blender UI
76 | def DisplayMessageBox(message = "", title = "Info", icon = 'INFO'):
77 | def draw(self, context):
78 | self.layout.label(text=message)
79 | bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
80 |
81 |
82 | # Class with functions for setting up shaders
83 | class shaderSetup():
84 |
85 | def createNode(mat, type, name="newNode", location=(0,0)):
86 | nodes = mat.node_tree.nodes
87 | n = nodes.new(type=type)
88 | n.name = name
89 | n.location = location
90 | return n
91 |
92 | def setMapping(node):
93 | tool = bpy.context.scene.assetlibrarytools
94 | if tool.texture_mapping == 'Object':
95 | node.projection = 'BOX'
96 | node.projection_blend = 1
97 |
98 | def simplePrincipledSetup(name, files):
99 | tool = bpy.context.scene.assetlibrarytools
100 | # Create a new empty material
101 | mat = bpy.data.materials.new(name)
102 | mat.use_nodes = True
103 | nodes = mat.node_tree.nodes
104 | links = mat.node_tree.links
105 | nodes.clear() # Delete all nodes
106 |
107 | # Load textures
108 | diffuseTexture = None
109 | sssTexture = None
110 | metallicTexture = None
111 | specularTexture = None
112 | roughnessTexture = None
113 | emissionTexture = None
114 | alphaTexture = None
115 | normalTexture = None
116 | displacementTexture = None
117 | for i in files:
118 | t = FindPBRTextureType(i.name)
119 | if t == "diff":
120 | diffuseTexture = bpy.data.images.load(str(i))
121 | elif t == "sss":
122 | sssTexture = bpy.data.images.load(str(i))
123 | sssTexture.colorspace_settings.name = 'Non-Color'
124 | elif t == "met":
125 | metallicTexture = bpy.data.images.load(str(i))
126 | metallicTexture.colorspace_settings.name = 'Non-Color'
127 | elif t == "spec":
128 | specularTexture = bpy.data.images.load(str(i))
129 | specularTexture.colorspace_settings.name = 'Non-Color'
130 | elif t == "rough":
131 | roughnessTexture = bpy.data.images.load(str(i))
132 | roughnessTexture.colorspace_settings.name = 'Non-Color'
133 | elif t == "emission":
134 | emissionTexture = bpy.data.images.load(str(i))
135 | elif t == "alpha":
136 | alphaTexture = bpy.data.images.load(str(i))
137 | alphaTexture.colorspace_settings.name = 'Non-Color'
138 | elif t == "norm":
139 | normalTexture = bpy.data.images.load(str(i))
140 | normalTexture.colorspace_settings.name = 'Non-Color'
141 | elif t == "disp":
142 | displacementTexture = bpy.data.images.load(str(i))
143 | displacementTexture.colorspace_settings.name = 'Non-Color'
144 |
145 | # Create base nodes
146 | node_output = shaderSetup.createNode(mat, "ShaderNodeOutputMaterial", "node_output", (250,0))
147 | node_principled = shaderSetup.createNode(mat, "ShaderNodeBsdfPrincipled", "node_principled", (-300,0))
148 | links.new(node_principled.outputs['BSDF'], node_output.inputs['Surface'])
149 | node_mapping = shaderSetup.createNode(mat, "ShaderNodeMapping", "node_mapping", (-1300,0))
150 | node_texCoord = shaderSetup.createNode(mat, "ShaderNodeTexCoord", "node_texCoord", (-1500,0))
151 | links.new(node_texCoord.outputs[tool.texture_mapping], node_mapping.inputs['Vector'])
152 | if tool.add_extranodes:
153 | node_scaleValue = shaderSetup.createNode(mat, "ShaderNodeValue", "node_scaleValue", (-1500, -300))
154 | node_scaleValue.outputs['Value'].default_value = 1
155 | links.new(node_scaleValue.outputs['Value'], node_mapping.inputs['Scale'])
156 |
157 | # Create, fill, and link texture nodes
158 | imported_tex_nodes = 0
159 | if diffuseTexture != None and tool.import_diff != False:
160 | node_imTexDiffuse = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexDiffuse", (-800,300-(300*imported_tex_nodes)))
161 | node_imTexDiffuse.image = diffuseTexture
162 | links.new(node_imTexDiffuse.outputs['Color'], node_principled.inputs['Base Color'])
163 | links.new(node_mapping.outputs['Vector'], node_imTexDiffuse.inputs['Vector'])
164 | shaderSetup.setMapping(node_imTexDiffuse)
165 | imported_tex_nodes += 1
166 |
167 | if sssTexture != None and tool.import_sss != False:
168 | node_imTexSSS = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexSSS", (-800,300-(300*imported_tex_nodes)))
169 | node_imTexSSS.image = sssTexture
170 | links.new(node_imTexSSS.outputs['Color'], node_principled.inputs['Subsurface'])
171 | links.new(node_mapping.outputs['Vector'], node_imTexSSS.inputs['Vector'])
172 | shaderSetup.setMapping(node_imTexSSS)
173 | imported_tex_nodes += 1
174 |
175 | if metallicTexture != None and tool.import_met != False:
176 | node_imTexMetallic = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexMetallic", (-800,300-(300*imported_tex_nodes)))
177 | node_imTexMetallic.image = metallicTexture
178 | links.new(node_imTexMetallic.outputs['Color'], node_principled.inputs['Metallic'])
179 | links.new(node_mapping.outputs['Vector'], node_imTexMetallic.inputs['Vector'])
180 | shaderSetup.setMapping(node_imTexMetallic)
181 | imported_tex_nodes += 1
182 |
183 | if specularTexture != None and tool.import_spec != False:
184 | node_imTexSpecular = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexSpecular", (-800,300-(300*imported_tex_nodes)))
185 | node_imTexSpecular.image = specularTexture
186 | links.new(node_imTexSpecular.outputs['Color'], node_principled.inputs['Specular'])
187 | links.new(node_mapping.outputs['Vector'], node_imTexSpecular.inputs['Vector'])
188 | shaderSetup.setMapping(node_imTexSpecular)
189 | imported_tex_nodes += 1
190 |
191 | if roughnessTexture != None and tool.import_rough != False:
192 | node_imTexRoughness = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexRoughness", (-800,300-(300*imported_tex_nodes)))
193 | node_imTexRoughness.image = roughnessTexture
194 | if tool.add_extranodes:
195 | node_imTexRoughnessColourRamp = shaderSetup.createNode(mat, "ShaderNodeValToRGB", "node_imTexRoughnessColourRamp", (-550,300-(300*imported_tex_nodes)))
196 | links.new(node_imTexRoughness.outputs['Color'], node_imTexRoughnessColourRamp.inputs['Fac'])
197 | links.new(node_imTexRoughnessColourRamp.outputs['Color'], node_principled.inputs['Roughness'])
198 | else:
199 | links.new(node_imTexRoughness.outputs['Color'], node_principled.inputs['Roughness'])
200 | links.new(node_mapping.outputs['Vector'], node_imTexRoughness.inputs['Vector'])
201 | shaderSetup.setMapping(node_imTexRoughness)
202 | imported_tex_nodes += 1
203 |
204 | if emissionTexture != None and tool.import_emission != False:
205 | node_imTexEmission = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexEmission", (-800,300-(300*imported_tex_nodes)))
206 | node_imTexEmission.image = emissionTexture
207 | links.new(node_imTexEmission.outputs['Color'], node_principled.inputs['Emission'])
208 | links.new(node_mapping.outputs['Vector'], node_imTexEmission.inputs['Vector'])
209 | shaderSetup.setMapping(node_imTexEmission)
210 | imported_tex_nodes += 1
211 |
212 | if alphaTexture != None and tool.import_alpha != False:
213 | node_imTexAlpha = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexAlpha", (-800,300-(300*imported_tex_nodes)))
214 | node_imTexAlpha.image = alphaTexture
215 | links.new(node_imTexAlpha.outputs['Color'], node_principled.inputs['Alpha'])
216 | links.new(node_mapping.outputs['Vector'], node_imTexAlpha.inputs['Vector'])
217 | shaderSetup.setMapping(node_imTexAlpha)
218 | imported_tex_nodes += 1
219 |
220 | if normalTexture != None and tool.import_norm != False:
221 | node_imTexNormal = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexNormal", (-800,300-(300*imported_tex_nodes)))
222 | node_imTexNormal.image = normalTexture
223 | node_normalMap = shaderSetup.createNode(mat, "ShaderNodeNormalMap", "node_normalMap", (-500,300-(300*imported_tex_nodes)))
224 | links.new(node_imTexNormal.outputs['Color'], node_normalMap.inputs['Color'])
225 | links.new(node_normalMap.outputs['Normal'], node_principled.inputs['Normal'])
226 | links.new(node_mapping.outputs['Vector'], node_imTexNormal.inputs['Vector'])
227 | shaderSetup.setMapping(node_imTexNormal)
228 | imported_tex_nodes += 1
229 |
230 | if displacementTexture != None and tool.import_disp != False:
231 | node_imTexDisplacement = shaderSetup.createNode(mat, "ShaderNodeTexImage", "node_imTexDisplacement", (-800,300-(300*imported_tex_nodes)))
232 | node_imTexDisplacement.image = displacementTexture
233 | node_imTexDisplacement.interpolation = 'Smart'
234 | node_displacement = shaderSetup.createNode(mat, "ShaderNodeDisplacement", "node_displacement", (-200,-600))
235 | links.new(node_imTexDisplacement.outputs['Color'], node_displacement.inputs['Height'])
236 | links.new(node_displacement.outputs['Displacement'], node_output.inputs['Displacement'])
237 | links.new(node_mapping.outputs['Vector'], node_imTexDisplacement.inputs['Vector'])
238 | shaderSetup.setMapping(node_imTexDisplacement)
239 | imported_tex_nodes += 1
240 |
241 | return mat
242 |
243 |
244 | # This code is bad!!!!
245 | # But i dont want to fix it!!!!
246 | def listDownloadAttribs(scene, context):
247 | scene = context.scene
248 | tool = scene.assetlibrarytools
249 | if tool.showAllDownloadAttribs == True:
250 | attribs = ['None', '1K-JPG', '1K-PNG', '2K-JPG', '2K-PNG', '4K-JPG', '4K-PNG', '8K-JPG', '8K-PNG', '12K-HDR', '16K-HDR', '1K-HDR', '2K-HDR', '4K-HDR', '8K-HDR', '12K-TONEMAPPED', '16K-TONEMAPPED', '1K-TONEMAPPED', '2K-TONEMAPPED', '4K-TONEMAPPED', '8K-TONEMAPPED', '12K-JPG', '12K-PNG', '16K-JPG', '16K-PNG', '1K-HQ-JPG', '1K-HQ-PNG', '1K-LQ-JPG', '1K-LQ-PNG', '1K-SQ-JPG', '1K-SQ-PNG', '2K-HQ-JPG', '2K-HQ-PNG', '2K-LQ-JPG', '2K-LQ-PNG', '2K-SQ-JPG', '2K-SQ-PNG', '4K-HQ-JPG', '4K-HQ-PNG', '4K-LQ-JPG', '4K-LQ-PNG', '4K-SQ-JPG', '4K-SQ-PNG', 'HQ', 'LQ', 'SQ', '24K-JPG', '24K-PNG', '32K-JPG', '32K-PNG', '6K-JPG', '6K-PNG', '2K', '4K', '8K', '1K', 'CustomImages', '16K', '9K', '1000K', '250K', '25K', '5K-JPG', '5K-PNG', '2kPNG', '4kPNG', '2kPNG-PNG', '4kPNG-PNG', '9K-JPG', '10K-JPG', '7K-JPG', '7K-PNG', '3K-JPG', '3K-PNG', '9K-PNG', '33K-JPG', '33K-PNG', '15K-JPG', '15K-PNG']
251 | else:
252 | attribs = ['None', '1K-JPG', '1K-PNG', '2K-JPG', '2K-PNG', '4K-JPG', '4K-PNG', '8K-JPG', '8K-PNG']
253 | items = []
254 | for a in attribs:
255 | items.append((a, a, ""))
256 | return items
257 |
258 |
259 | # ------------------------------------------------------------------------
260 | # Properties
261 | # ------------------------------------------------------------------------
262 |
263 | class properties(PropertyGroup):
264 |
265 | # Material import properties
266 | mat_import_path : StringProperty(
267 | name = "Import directory",
268 | description = "Choose a directory to batch import PBR texture sets from.\nFormat your files like this: ChosenDirectory/PBRTextureName/textureFiles",
269 | default = "",
270 | maxlen = 1024,
271 | subtype = 'DIR_PATH'
272 | )
273 | skip_existing : BoolProperty(
274 | name = "Skip existing",
275 | description = "Dont import materials if a material with the same name already exists",
276 | default = True
277 | )
278 | tex_ignore_filter : StringProperty(
279 | name = "Tex name filter",
280 | description = "Filter unwanted textures by a common string in the name (such as DX, which denotes a directX normal map)",
281 | default = "",
282 | maxlen = 1024,
283 | )
284 | use_fake_user : BoolProperty(
285 | name = "Use fake user",
286 | description = "Use fake user on imported materials",
287 | default = True
288 | )
289 | use_real_displacement : BoolProperty(
290 | name = "Use real displacement",
291 | description = "Enable real geometry displacement in the material settings (cycles only)",
292 | default = False
293 | )
294 | add_extranodes : BoolProperty(
295 | name = "Add utility nodes",
296 | description = "Adds nodes to the imported materials for easy control",
297 | default = False
298 | )
299 | texture_mapping : EnumProperty(
300 | name='Mapping',
301 | default='UV',
302 | items=[('UV', 'UV', 'Use UVs to control mapping'),
303 | ('Object', 'Object', 'Wrap texture along world coords')])
304 | import_diff : BoolProperty(
305 | name = "Import diffuse",
306 | description = "",
307 | default = True
308 | )
309 | import_sss : BoolProperty(
310 | name = "Import SSS",
311 | description = "",
312 | default = True
313 | )
314 | import_met : BoolProperty(
315 | name = "Import metallic",
316 | description = "",
317 | default = True
318 | )
319 | import_spec : BoolProperty(
320 | name = "Import specularity",
321 | description = "",
322 | default = True
323 | )
324 | import_rough : BoolProperty(
325 | name = "Import roughness",
326 | description = "",
327 | default = True
328 | )
329 | import_emission : BoolProperty(
330 | name = "Import emission",
331 | description = "",
332 | default = True
333 | )
334 | import_alpha : BoolProperty(
335 | name = "Import alpha",
336 | description = "",
337 | default = True
338 | )
339 | import_norm : BoolProperty(
340 | name = "Import normal",
341 | description = "",
342 | default = True
343 | )
344 | import_disp : BoolProperty(
345 | name = "Import displacement",
346 | description = "",
347 | default = True
348 | )
349 |
350 |
351 | # Model import properties
352 | model_import_path : StringProperty(
353 | name = "Import directory",
354 | description = "Choose a directory to batch import models from.\nSubdirectories are checked recursively",
355 | default = "",
356 | maxlen = 1024,
357 | subtype = 'DIR_PATH'
358 | )
359 | hide_after_import : BoolProperty(
360 | name = "Hide models after import",
361 | description = "Reduces viewport polycount, prevents low framerate/crashes.\nHides each model individually straight after import",
362 | default = False
363 | )
364 | move_to_new_collection_after_import : BoolProperty(
365 | name = "Move models to new collection after import",
366 | description = "",
367 | default = False
368 | )
369 | join_new_objects : BoolProperty(
370 | name = "Join all models in each file together after import",
371 | description = "",
372 | default = False
373 | )
374 | import_fbx : BoolProperty(
375 | name = "Import FBX files",
376 | description = "",
377 | default = True
378 | )
379 | import_gltf : BoolProperty(
380 | name = "Import GLTF files",
381 | description = "",
382 | default = True
383 | )
384 | import_obj : BoolProperty(
385 | name = "Import OBJ files",
386 | description = "",
387 | default = True
388 | )
389 | import_x3d : BoolProperty(
390 | name = "Import X3D files",
391 | description = "",
392 | default = True
393 | )
394 |
395 |
396 | # Batch append properties
397 | append_path : StringProperty(
398 | name = "Import directory",
399 | description = "Choose a directory to batch append from.",
400 | default = "",
401 | maxlen = 1024,
402 | subtype = 'DIR_PATH'
403 | )
404 | append_recursive_search : BoolProperty(
405 | name = "Search for .blend files in subdirs recursively",
406 | description = "",
407 | default = False
408 | )
409 | append_move_to_new_collection_after_import : BoolProperty(
410 | name = "Move objects to new collection after import",
411 | description = "",
412 | default = False
413 | )
414 | append_join_new_objects : BoolProperty(
415 | name = "Join all objects in each file together after import",
416 | description = "",
417 | default = False
418 | )
419 | appendType : EnumProperty(
420 | name="Append",
421 | description="Choose type to append",
422 | items=[ ('objects', "Objects", ""),
423 | ('materials', "Materials", ""),
424 | ]
425 | )
426 | deleteLights : BoolProperty(
427 | name = "Dont append lights",
428 | description = "",
429 | default = True
430 | )
431 | deleteCameras : BoolProperty(
432 | name = "Dont append cameras",
433 | description = "",
434 | default = True
435 | )
436 |
437 |
438 | # Asset management properties
439 | markunmark : EnumProperty(
440 | name="Operation",
441 | description="Choose whether to mark assets, or unmark assets",
442 | items=[ ('mark', "Mark assets", ""),
443 | ('unmark', "Unmark assets", ""),
444 | ]
445 | )
446 | assettype : EnumProperty(
447 | name="On type",
448 | description="Choose a type of asset to mark/unmark",
449 | items=[ ('objects', "Objects", ""),
450 | ('materials', "Materials", ""),
451 | ('images', "Images", ""),
452 | ('textures', "Textures", ""),
453 | ('meshes', "Meshes", ""),
454 | ]
455 | )
456 | previewgentype : EnumProperty(
457 | name="Asset type",
458 | description="Choose a type of asset to mark/unmark",
459 | items=[ ('objects', "Objects", ""),
460 | ('materials', "Materials", ""),
461 | ('images', "Images", ""),
462 | ('textures', "Textures", ""),
463 | ('meshes', "Meshes", ""),
464 | ]
465 | )
466 |
467 |
468 | # Utilities panel properties
469 | deleteType : EnumProperty(
470 | name="Delete all",
471 | description="Choose type to batch delete",
472 | items=[ ('objects', "Objects", ""),
473 | ('materials', "Materials", ""),
474 | ('images', "Images", ""),
475 | ('textures', "Textures", ""),
476 | ('meshes', "Meshes", ""),
477 | ]
478 | )
479 | dispNewScale: FloatProperty(
480 | name = "New Displacement Scale",
481 | description = "A float property",
482 | default = 0.1,
483 | min = 0.0001
484 | )
485 |
486 |
487 | # Asset snapshot panel properties
488 | resolution : IntProperty(
489 | name="Preview Resolution",
490 | description="Resolution to render the preview",
491 | min=1,
492 | soft_max=500,
493 | default=256
494 | )
495 |
496 |
497 | # CC0AssetDownloader properties
498 | downloader_save_path : StringProperty(
499 | name = "Save location",
500 | description = "Choose a directory to save assets to",
501 | default = "",
502 | maxlen = 1024,
503 | subtype = 'DIR_PATH'
504 | )
505 | keywordFilter : StringProperty(
506 | name = "Keyword filter",
507 | description = "Enter a keyword to filter assets by, leave empty if you do not wish to filter.",
508 | default = "",
509 | maxlen = 1024,
510 | )
511 | showAllDownloadAttribs: BoolProperty(
512 | name = "Show all download attributes",
513 | description = "",
514 | default = True
515 | )
516 | attributeFilter : EnumProperty(
517 | name="Attribute filter",
518 | description="Choose attribute to filter assets by",
519 | items=listDownloadAttribs
520 | )
521 | extensionFilter : EnumProperty(
522 | name="Extension filter",
523 | description="Choose file extension to filter assets by",
524 | items=[ ('None', "None", ""),
525 | ('zip', "ZIP", ""),
526 | ('obj', "OBJ", ""),
527 | ('exr', "EXR", ""),
528 | ('sbsar', "SBSAR", ""),
529 | ]
530 | )
531 | unZip : BoolProperty(
532 | name = "Unzip downloaded zip files",
533 | description = "",
534 | default = True
535 | )
536 | deleteZips : BoolProperty(
537 | name = "Delete zip files after they have been unzipped",
538 | description = "",
539 | default = True
540 | )
541 | skipDuplicates : BoolProperty(
542 | name = "Dont download files which already exist",
543 | description = "",
544 | default = True
545 | )
546 | terminal : EnumProperty(
547 | name="Terminal",
548 | description="Choose terminal to run script with",
549 | items=[ ('cmd', "cmd", ""),
550 | ('gnome-terminal', "gnome-terminal", ""),
551 | ('konsole', 'konsole', ""),
552 | ('xterm', 'xterm', ""),
553 | ]
554 | )
555 |
556 |
557 | # SBSAR import properties
558 | sbsar_import_path : StringProperty(
559 | name = "Import directory",
560 | description = "Choose a directory to batch import sbsar files from.\nSubdirectories are checked recursively",
561 | default = "",
562 | maxlen = 1024,
563 | subtype = 'DIR_PATH'
564 | )
565 |
566 |
567 | # UI properties
568 | matImport_expanded : BoolProperty(
569 | name = "Click to expand",
570 | description = "",
571 | default = False
572 | )
573 | matImportOptions_expanded : BoolProperty(
574 | name = "Click to expand",
575 | description = "",
576 | default = False
577 | )
578 | append_expanded : BoolProperty(
579 | name = "Click to expand",
580 | description = "",
581 | default = False
582 | )
583 | modelImport_expanded : BoolProperty(
584 | name = "Click to expand",
585 | description = "",
586 | default = False
587 | )
588 | modelImportOptions_expanded : BoolProperty(
589 | name = "Click to expand",
590 | description = "",
591 | default = False
592 | )
593 | assetBrowserOpsRow_expanded : BoolProperty(
594 | name = "Click to expand",
595 | description = "",
596 | default = False
597 | )
598 | utilRow_expanded : BoolProperty(
599 | name = "Click to expand",
600 | description = "",
601 | default = False
602 | )
603 | snapshotRow_expanded : BoolProperty(
604 | name = "Click to expand",
605 | description = "",
606 | default = False
607 | )
608 | assetDownloaderRow_expanded : BoolProperty(
609 | name = "Click to expand",
610 | description = "",
611 | default = False
612 | )
613 | sbsarImport_expanded : BoolProperty(
614 | name = "Click to expand",
615 | description = "",
616 | default = False
617 | )
618 |
619 | # ------------------------------------------------------------------------
620 | # Operators
621 | # ------------------------------------------------------------------------
622 |
623 | class OT_BatchImportPBR(Operator):
624 | bl_label = "Import PBR textures"
625 | bl_idname = "alt.batchimportpbr"
626 | def execute(self, context):
627 | scene = context.scene
628 | tool = scene.assetlibrarytools
629 | n_imp = 0 # Number of materials imported
630 | n_del = 0 # Number of materials deleted (due to no textures after import)
631 | n_skp = 0 # Number of materials skipped due to them already existing
632 | existing_mat_names = []
633 | subdirectories = [x for x in pathlib.Path(tool.mat_import_path).iterdir() if x.is_dir()] # Get subdirs in directory selected in UI
634 | for sd in subdirectories:
635 | filePaths = [x for x in pathlib.Path(sd).iterdir() if x.is_file()] # Get filepaths of textures
636 | if tool.tex_ignore_filter != "": # Remove filepaths of textures which contain a filtered string, if a filter is chosen.
637 | for fp in filePaths:
638 | if tool.tex_ignore_filter in fp.name:
639 | filePaths.pop(filePaths.index(fp))
640 | # Get existing material names if skipping existing materials is turned on
641 | if tool.skip_existing == True:
642 | existing_mat_names = []
643 | for mat in bpy.data.materials:
644 | existing_mat_names.append(mat.name)
645 | # check if the material thats about to be imported exists or not, or if we dont care about skipping existing materials.
646 | if (sd.name not in existing_mat_names) or (tool.skip_existing != True):
647 | mat = shaderSetup.simplePrincipledSetup(sd.name, filePaths) # Create shader using filepaths of textures
648 | if tool.use_fake_user == True: # Enable fake user (if desired)
649 | mat.use_fake_user = True
650 | if tool.use_real_displacement == True: # Enable real displacement (if desired)
651 | mat.cycles.displacement_method = 'BOTH'
652 | # Delete the material if it contains no textures
653 | hasTex = False
654 | for n in mat.node_tree.nodes:
655 | if n.type == 'TEX_IMAGE': # Check if shader contains textures, if yes, then its worth keeping
656 | hasTex = True
657 | if hasTex == False:
658 | bpy.data.materials.remove(mat) # Delete material if it contains no textures
659 | n_del += 1
660 | else:
661 | n_imp += 1
662 | else:
663 | n_skp += 1
664 | if (n_del > 0) and (n_skp > 0):
665 | DisplayMessageBox("Complete, {0} materials imported, {1} were deleted after import because they contained no textures (No recognised textures were found in the folder), {2} skipped because they already exist".format(n_imp,n_del,n_skp))
666 | elif n_skp > 0:
667 | DisplayMessageBox("Complete, {0} materials imported. {1} skipped because they already exist".format(n_imp, n_skp))
668 | elif n_del > 0:
669 | DisplayMessageBox("Complete, {0} materials imported, {1} were deleted after import because they contained no textures (No recognised textures were found in the folder)".format(n_imp,n_del))
670 | else:
671 | DisplayMessageBox("Complete, {0} materials imported".format(n_imp))
672 | return{'FINISHED'}
673 |
674 |
675 | class OT_ImportModels(Operator):
676 | bl_label = "Import models"
677 | bl_idname = "alt.importmodels"
678 |
679 | # Hide new objects works by comparing a list of objects before (x) happened with the current list via bpy.context.scene.objects to get the list of new objects, then hides those new objects
680 | def hideNewObjects(old_objects):
681 | scene = bpy.context.scene
682 | tool = scene.assetlibrarytools
683 | if tool.hide_after_import == True:
684 | imported_objects = set(bpy.context.scene.objects) - old_objects
685 | for object in imported_objects:
686 | object.hide_set(True)
687 |
688 | def moveNewObjectsToNewCollection(old_objects, collName):
689 | scene = bpy.context.scene
690 | tool = scene.assetlibrarytools
691 | if tool.move_to_new_collection_after_import == True:
692 | imported_objects = set(bpy.context.scene.objects) - old_objects
693 | newCollection = bpy.data.collections.new(collName)
694 | bpy.context.scene.collection.children.link(newCollection)
695 | for obj in imported_objects:
696 | for uc in obj.users_collection:
697 | uc.objects.unlink(obj)
698 | newCollection.objects.link(obj)
699 |
700 | def joinAllNewObjects(old_objects):
701 | scene = bpy.context.scene
702 | tool = scene.assetlibrarytools
703 | if tool.join_new_objects == True:
704 | imported_objects = set(bpy.context.scene.objects) - old_objects
705 | bpy.ops.object.select_all(action='DESELECT')
706 | for obj in imported_objects:
707 | bpy.context.view_layer.objects.active = obj
708 | obj.select_set(True)
709 | bpy.ops.object.join()
710 |
711 | def execute(self, context):
712 | scene = context.scene
713 | tool = scene.assetlibrarytools
714 | p = pathlib.Path(str(tool.model_import_path))
715 | imported = 0 # Number of imported objects
716 | errors = 0 # Number of import errors
717 | # Import FBX files
718 | if tool.import_fbx == True:
719 | fbxFilePaths = [x for x in p.glob('**/*.fbx') if x.is_file()] # Get filepaths of files with the extension .fbx in the selected directory (and subdirs, recursively)
720 | for filePath in fbxFilePaths:
721 | old_objects = set(context.scene.objects)
722 | try:
723 | bpy.ops.import_scene.fbx(filepath=str(filePath))
724 | imported += 1
725 | except:
726 | print("FBX import error")
727 | errors += 1
728 | OT_ImportModels.hideNewObjects(old_objects)
729 | OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
730 | OT_ImportModels.joinAllNewObjects(old_objects)
731 | # Import GLTF files
732 | if tool.import_gltf == True:
733 | gltfFilePaths = [x for x in p.glob('**/*.gltf') if x.is_file()] # Get filepaths of files with the extension .gltf in the selected directory (and subdirs, recursively)
734 | for filePath in gltfFilePaths:
735 | old_objects = set(context.scene.objects)
736 | try:
737 | bpy.ops.import_scene.gltf(filepath=str(filePath))
738 | imported += 1
739 | except:
740 | print("GLTF import error")
741 | errors += 1
742 | OT_ImportModels.hideNewObjects(old_objects)
743 | OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
744 | OT_ImportModels.joinAllNewObjects(old_objects)
745 | # Import OBJ files
746 | if tool.import_obj == True:
747 | objFilePaths = [x for x in p.glob('**/*.obj') if x.is_file()] # Get filepaths of files with the extension .obj in the selected directory (and subdirs, recursively)
748 | for filePath in objFilePaths:
749 | old_objects = set(context.scene.objects)
750 | try:
751 | bpy.ops.import_scene.obj(filepath=str(filePath))
752 | imported += 1
753 | except:
754 | print("OBJ import error")
755 | errors += 1
756 | OT_ImportModels.hideNewObjects(old_objects)
757 | OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
758 | OT_ImportModels.joinAllNewObjects(old_objects)
759 | # Import X3D files
760 | if tool.import_x3d == True:
761 | x3dFilePaths = [x for x in p.glob('**/*.x3d') if x.is_file()] # Get filepaths of files with the extension .x3d in the selected directory (and subdirs, recursively)
762 | for filePath in x3dFilePaths:
763 | old_objects = set(context.scene.objects)
764 | try:
765 | bpy.ops.import_scene.x3d(filepath=str(filePath))
766 | imported += 1
767 | except:
768 | print("X3D import error")
769 | errors += 1
770 | OT_ImportModels.hideNewObjects(old_objects)
771 | OT_ImportModels.moveNewObjectsToNewCollection(old_objects, filePath.name)
772 | OT_ImportModels.joinAllNewObjects(old_objects)
773 | if errors == 0:
774 | DisplayMessageBox("Complete, {0} models imported".format(imported))
775 | else:
776 | DisplayMessageBox("Complete, {0} models imported. {1} import errors".format(imported, errors))
777 | return{'FINISHED'}
778 |
779 |
780 | class OT_BatchAppend(Operator):
781 | bl_label = "Append"
782 | bl_idname = "alt.batchappend"
783 | def execute(self, context):
784 | scene = context.scene
785 | tool = scene.assetlibrarytools
786 | p = pathlib.Path(str(tool.append_path))
787 | link = False # append, set to true to keep the link to the original file
788 | if tool.append_recursive_search == True:
789 | blendFilePaths = [x for x in p.glob('**/*.blend') if x.is_file()] # Get filepaths of files with the extension .blend in the selected directory (and subdirs, recursively)
790 | else:
791 | blendFilePaths = [x for x in p.glob('*.blend') if x.is_file()] # Get filepaths of files with the extension .blend in the selected directory
792 | for path in blendFilePaths:
793 | if tool.appendType == 'objects':
794 | # link all objects
795 | with bpy.data.libraries.load(str(path), link=link) as (data_from, data_to):
796 | data_to.objects = data_from.objects
797 | # Create new collection
798 | if tool.append_move_to_new_collection_after_import:
799 | newCollection = bpy.data.collections.new(str(path.name))
800 | bpy.context.scene.collection.children.link(newCollection)
801 | #link object to collection
802 | for obj in data_to.objects:
803 | removed = False
804 | if obj != None:
805 | if tool.append_move_to_new_collection_after_import:
806 | newCollection.objects.link(obj)
807 | else:
808 | bpy.context.collection.objects.link(obj)
809 | # remove cameras
810 | if removed == False and tool.deleteCameras == True: # This stops an error from occuring if obj is already deleted
811 | if obj.type == 'CAMERA':
812 | bpy.data.objects.remove(obj)
813 | removed = True
814 | # remove lights
815 | if removed == False and tool.deleteLights == True: # This stops an error from occuring if obj is already deleted
816 | if obj.type == 'LIGHT':
817 | bpy.data.objects.remove(obj)
818 | removed = True
819 | # Join objects if option turned on
820 | if tool.append_join_new_objects:
821 | bpy.ops.object.select_all(action='DESELECT')
822 | for obj in data_to.objects:
823 | bpy.context.view_layer.objects.active = obj
824 | obj.select_set(True)
825 | bpy.ops.object.join()
826 |
827 | if tool.appendType == 'materials':
828 | with bpy.data.libraries.load(str(path), link=link) as (data_from, data_to):
829 | data_to.materials = data_from.materials
830 | if tool.appendType == 'objects':
831 | DisplayMessageBox("Complete, objects appended")
832 | if tool.appendType == 'materials':
833 | DisplayMessageBox("Complete, materials appended")
834 | return{'FINISHED'}
835 |
836 |
837 | class OT_ManageAssets(Operator):
838 | bl_label = "Go"
839 | bl_idname = "alt.manageassets"
840 | def execute(self, context):
841 | scene = context.scene
842 | tool = scene.assetlibrarytools
843 | i = 0 # Number of assets modified
844 | # Mark assets
845 | if tool.markunmark == 'mark':
846 | if tool.assettype == 'objects':
847 | for object in bpy.data.objects:
848 | object.asset_mark()
849 | i += 1
850 | if tool.assettype == 'materials':
851 | for mat in bpy.data.materials:
852 | mat.asset_mark()
853 | i += 1
854 | if tool.assettype == 'images':
855 | for image in bpy.data.images:
856 | image.asset_mark()
857 | i += 1
858 | if tool.assettype == 'textures':
859 | for texture in bpy.data.textures:
860 | texture.asset_mark()
861 | i += 1
862 | if tool.assettype == 'meshes':
863 | for mesh in bpy.data.meshes:
864 | mesh.asset_mark()
865 | i += 1
866 | DisplayMessageBox("Complete, {0} assets marked".format(i))
867 | # Unmark assets
868 | if tool.markunmark == 'unmark':
869 | if tool.assettype == 'objects':
870 | for object in bpy.data.objects:
871 | object.asset_clear()
872 | i += 1
873 | if tool.assettype == 'materials':
874 | for mat in bpy.data.materials:
875 | mat.asset_clear()
876 | i += 1
877 | if tool.assettype == 'images':
878 | for image in bpy.data.images:
879 | image.asset_clear()
880 | i += 1
881 | if tool.assettype == 'textures':
882 | for texture in bpy.data.textures:
883 | texture.asset_clear()
884 | i += 1
885 | if tool.assettype == 'meshes':
886 | for mesh in bpy.data.meshes:
887 | mesh.asset_clear()
888 | i += 1
889 | DisplayMessageBox("Complete, {0} assets unmarked".format(i))
890 | return {'FINISHED'}
891 |
892 |
893 | class OT_GenerateAssetPreviews(Operator):
894 | bl_label = "Generate previews"
895 | bl_idname = "alt.generateassetpreviews"
896 | def execute(self, context):
897 | scene = context.scene
898 | tool = scene.assetlibrarytools
899 | if tool.previewgentype == 'objects':
900 | for obj in bpy.data.objects:
901 | if obj.asset_data:
902 | obj.asset_generate_preview()
903 | if tool.previewgentype == 'materials':
904 | for mat in bpy.data.materials:
905 | if mat.asset_data:
906 | mat.asset_generate_preview()
907 | if tool.previewgentype == 'images':
908 | for img in bpy.data.images:
909 | if img.asset_data:
910 | img.asset_generate_preview()
911 | if tool.previewgentype == 'textures':
912 | for tex in bpy.data.textures:
913 | if tex.asset_data:
914 | tex.asset_generate_preview()
915 | if tool.previewgentype == 'meshes':
916 | for mesh in bpy.data.meshes:
917 | if mesh.asset_data:
918 | mesh.asset_generate_preview()
919 | return {'FINISHED'}
920 |
921 |
922 | class OT_BatchDelete(Operator):
923 | bl_label = "Go"
924 | bl_idname = "alt.batchdelete"
925 | def execute(self, context):
926 | scene = context.scene
927 | tool = scene.assetlibrarytools
928 | i = 0 # Number of items deleted
929 | if tool.deleteType == 'objects':
930 | for object in bpy.data.objects:
931 | bpy.data.objects.remove(object)
932 | i += 1
933 | if tool.deleteType == 'materials':
934 | for mat in bpy.data.materials:
935 | bpy.data.materials.remove(mat)
936 | i += 1
937 | if tool.deleteType == 'images':
938 | while len(bpy.data.images) > 0: # Cant use a for loop like the other "delete all" operations for some reason
939 | bpy.data.images.remove(bpy.data.images[0])
940 | i += 1
941 | if tool.deleteType == 'textures':
942 | for tex in bpy.data.textures:
943 | bpy.data.textures.remove(tex)
944 | i += 1
945 | if tool.deleteType == 'meshes':
946 | for mesh in bpy.data.meshes:
947 | bpy.data.meshes.remove(mesh)
948 | i += 1
949 | DisplayMessageBox("Done, {0} {1} deleted".format(i, tool.deleteType))
950 | return {'FINISHED'}
951 |
952 |
953 | class OT_SimpleDelDupeMaterials(Operator):
954 | bl_label = "Clean up duplicate materials (simple)"
955 | bl_idname = "alt.simpledeldupemats"
956 | def execute(self, context):
957 | for obj in bpy.data.objects:
958 | for slt in obj.material_slots:
959 | part = slt.name.rpartition('.')
960 | if part[2].isnumeric() and part[0] in bpy.data.materials:
961 | slt.material = bpy.data.materials.get(part[0])
962 | DisplayMessageBox("Done")
963 | return {'FINISHED'}
964 |
965 |
966 | class OT_CleanupUnusedMaterials(Operator):
967 | bl_label = "Clean up unused materials"
968 | bl_idname = "alt.cleanupunusedmats"
969 | def execute(self, context):
970 | i = 0
971 | for mat in bpy.data.materials:
972 | if mat.users == 0:
973 | bpy.data.materials.remove(mat)
974 | i += 1
975 | DisplayMessageBox("Done, {0} unused materials deleted".format(i))
976 | return {'FINISHED'}
977 |
978 |
979 | class OT_UseDisplacementOnAll(Operator):
980 | bl_label = "Use real displacement on all materials"
981 | bl_idname = "alt.userealdispall"
982 | def execute(self, context):
983 | for mat in bpy.data.materials:
984 | mat.cycles.displacement_method = 'BOTH'
985 | DisplayMessageBox("Done")
986 | return {'FINISHED'}
987 |
988 |
989 | class OT_ChangeAllDisplacementScale(Operator):
990 | bl_label = "Change displacement scale on all materials"
991 | bl_idname = "alt.changealldispscale"
992 | def execute(self, context):
993 | tool = context.scene.assetlibrarytools
994 | i = 0 # number of nodes changed
995 | for mat in bpy.data.materials:
996 | if mat is not None and mat.use_nodes and mat.node_tree is not None:
997 | for node in mat.node_tree.nodes:
998 | if node.type == 'DISPLACEMENT':
999 | node.inputs[2].default_value = tool.dispNewScale
1000 | i += 1
1001 | DisplayMessageBox("Done, {0} nodes changed".format(i))
1002 | return {'FINISHED'}
1003 |
1004 |
1005 | def snapshot(self,context,ob):
1006 | scene = context.scene
1007 | tool = scene.assetlibrarytools
1008 | # Make sure we have a camera
1009 | if bpy.context.scene.camera == None:
1010 | bpy.ops.object.camera_add()
1011 |
1012 | #Save some basic settings
1013 | camera = bpy.context.scene.camera
1014 | hold_camerapos = camera.location.copy()
1015 | hold_camerarot = camera.rotation_euler.copy()
1016 | hold_x = bpy.context.scene.render.resolution_x
1017 | hold_y = bpy.context.scene.render.resolution_y
1018 | hold_filepath = bpy.context.scene.render.filepath
1019 |
1020 | # Find objects that are hidden in viewport and hide them in render
1021 | tempHidden = []
1022 | for o in bpy.data.objects:
1023 | if o.hide_get() == True:
1024 | o.hide_render = True
1025 | tempHidden.append(o)
1026 |
1027 | # Change Settings
1028 | bpy.context.scene.render.resolution_y = tool.resolution
1029 | bpy.context.scene.render.resolution_x = tool.resolution
1030 | switchback = False
1031 | if bpy.ops.view3d.camera_to_view.poll():
1032 | bpy.ops.view3d.camera_to_view()
1033 | switchback = True
1034 |
1035 | # Ensure outputfile is set to png (temporarily, at least)
1036 | previousFileFormat = scene.render.image_settings.file_format
1037 | if scene.render.image_settings.file_format != 'PNG':
1038 | scene.render.image_settings.file_format = 'PNG'
1039 |
1040 | filename = str(random.randint(0,100000000000))+".png"
1041 | filepath = str(os.path.abspath(os.path.join(os.sep, 'tmp', filename)))
1042 | bpy.context.scene.render.filepath = filepath
1043 |
1044 | #Render File, Mark Asset and Set Image
1045 | bpy.ops.render.render(write_still = True)
1046 | ob.asset_mark()
1047 | override = bpy.context.copy()
1048 | override['id'] = ob
1049 | bpy.ops.ed.lib_id_load_custom_preview(override,filepath=filepath)
1050 |
1051 | # Unhide the objects hidden for the render
1052 | for o in tempHidden:
1053 | o.hide_render = False
1054 | # Reset output file format
1055 | scene.render.image_settings.file_format = previousFileFormat
1056 |
1057 | #Cleanup
1058 | os.unlink(filepath)
1059 | bpy.context.scene.render.resolution_y = hold_y
1060 | bpy.context.scene.render.resolution_x = hold_x
1061 | camera.location = hold_camerapos
1062 | camera.rotation_euler = hold_camerarot
1063 | bpy.context.scene.render.filepath = hold_filepath
1064 | if switchback:
1065 | bpy.ops.view3d.view_camera()
1066 |
1067 |
1068 | class OT_AssetSnapshotCollection(Operator):
1069 | """Create a preview of a collection"""
1070 | bl_idname = "view3d.asset_snaphot_collection"
1071 | bl_label = "Asset Snapshot - Collection"
1072 | bl_options = {'REGISTER', 'UNDO'}
1073 | def execute(self, context):
1074 | snapshot(self, context,context.collection)
1075 | return {'FINISHED'}
1076 |
1077 |
1078 | class OT_AssetSnapshotObject(Operator):
1079 | """Create an asset preview of an object"""
1080 | bl_idname = "view3d.object_preview"
1081 | bl_label = "Asset Snapshot - Object"
1082 | bl_options = {'REGISTER', 'UNDO'}
1083 | def execute(self, context):
1084 | snapshot(self, context, bpy.context.view_layer.objects.active)
1085 | return {'FINISHED'}
1086 |
1087 |
1088 | class OT_AssetDownloaderOperator(Operator):
1089 | bl_label = "Run script"
1090 | bl_idname = "alt.assetdownloader"
1091 | def execute(self, context):
1092 | tool = context.scene.assetlibrarytools
1093 | ur = bpy.utils.user_resource('SCRIPTS')
1094 | # Do some input checking
1095 | if tool.downloader_save_path == '':
1096 | DisplayMessageBox("Enter a save path", "Error", "ERROR")
1097 | if ' ' in tool.downloader_save_path:
1098 | DisplayMessageBox("Filepath invalid: space in filepath", "Error", "ERROR")
1099 | if tool.keywordFilter == "":
1100 | tool.keywordFilter = 'None'
1101 | if ' ' not in tool.downloader_save_path and tool.downloader_save_path != '':
1102 | # Start ALT_CC0AssetDownloader.py via chosen terminal
1103 | if tool.terminal == 'xterm':
1104 | os.system('xterm -e "python3 {0}/ALT_CC0AssetDownloader.py {1} {2} {3} {4} {5} {6} {7}"'.format(ur+'/addons/AssetLibraryTools', tool.downloader_save_path, tool.keywordFilter, tool.attributeFilter, tool.extensionFilter, str(tool.unZip), str(tool.deleteZips), str(tool.skipDuplicates)))
1105 | if tool.terminal == 'konsole':
1106 | os.system('konsole -e "python3 {0}/ALT_CC0AssetDownloader.py {1} {2} {3} {4} {5} {6} {7}"'.format(ur+'/addons/AssetLibraryTools', tool.downloader_save_path, tool.keywordFilter, tool.attributeFilter, tool.extensionFilter, str(tool.unZip), str(tool.deleteZips), str(tool.skipDuplicates)))
1107 | if tool.terminal == 'gnome-terminal':
1108 | os.system('gnome-terminal -e "python3 {0}/ALT_CC0AssetDownloader.py {1} {2} {3} {4} {5} {6} {7}"'.format(ur+'/addons/AssetLibraryTools', tool.downloader_save_path, tool.keywordFilter, tool.attributeFilter, tool.extensionFilter, str(tool.unZip), str(tool.deleteZips), str(tool.skipDuplicates)))
1109 | if tool.terminal == 'cmd':
1110 | os.system('start cmd /k \"cd /D {0} & python ALT_CC0AssetDownloader.py {1} {2} {3} {4} {5} {6} {7}'.format(ur+'\\addons\\AssetLibraryTools', tool.downloader_save_path, tool.keywordFilter, tool.attributeFilter, tool.extensionFilter, str(tool.unZip), str(tool.deleteZips), str(tool.skipDuplicates)))
1111 | return {'FINISHED'}
1112 |
1113 |
1114 | class OT_ImportSBSAR(Operator):
1115 | bl_label = "Import SBSAR files"
1116 | bl_idname = "alt.importsbsar"
1117 | def execute(self, context):
1118 | scene = context.scene
1119 | tool = scene.assetlibrarytools
1120 | p = pathlib.Path(str(tool.sbsar_import_path))
1121 | i = 0 # number of files imported
1122 | files = [x for x in p.glob('**/*.sbsar') if x.is_file()] # Get filepaths of files with the extension .sbsar in the selected directory (and subdirs, recursively)
1123 | for f in files:
1124 | try:
1125 | bpy.ops.substance.load_sbsar(filepath=str(f), description_arg=True, files=[{"name":f.name, "name":f.name}], directory=str(f).replace(f.name, ""))
1126 | i += 1
1127 | except:
1128 | print("SBSAR import failure")
1129 | DisplayMessageBox("Complete, {0} sbsar files imported".format(i))
1130 | return{'FINISHED'}
1131 |
1132 |
1133 | # ------------------------------------------------------------------------
1134 | # UI
1135 | # ------------------------------------------------------------------------
1136 |
1137 | class OBJECT_PT_panel(Panel):
1138 | bl_label = "AssetLibraryTools"
1139 | bl_idname = "OBJECT_PT_assetlibrarytools_panel"
1140 | bl_category = "AssetLibraryTools"
1141 | bl_space_type = "VIEW_3D"
1142 | bl_region_type = "UI"
1143 |
1144 | @classmethod
1145 | def poll(self,context):
1146 | return context.mode
1147 |
1148 | def draw(self, context):
1149 | layout = self.layout
1150 | scene = context.scene
1151 | tool = scene.assetlibrarytools
1152 | obj = context.scene.assetlibrarytools
1153 |
1154 |
1155 | # Material import UI
1156 | matImportBox = layout.box()
1157 | matImportRow = matImportBox.row()
1158 | matImportRow.prop(obj, "matImport_expanded",
1159 | icon="TRIA_DOWN" if obj.matImport_expanded else "TRIA_RIGHT",
1160 | icon_only=True, emboss=False
1161 | )
1162 | matImportRow.label(text="Batch import PBR texture sets as simple materials")
1163 | if obj.matImport_expanded:
1164 | matImportBox.prop(tool, "mat_import_path")
1165 | matImportBox.label(text='Make sure to uncheck "Relative Path"!', icon="ERROR")
1166 | matImportBox.operator("alt.batchimportpbr")
1167 | matImportOptionsRow = matImportBox.row()
1168 | matImportOptionsRow.prop(obj, "matImportOptions_expanded",
1169 | icon="TRIA_DOWN" if obj.matImportOptions_expanded else "TRIA_RIGHT",
1170 | icon_only=True, emboss=False
1171 | )
1172 | matImportOptionsRow.label(text="Import options: ")
1173 | if obj.matImportOptions_expanded:
1174 | matImportOptionsRow = matImportBox.row()
1175 | matImportBox.label(text="Import settings:")
1176 | matImportBox.prop(tool, "skip_existing")
1177 | matImportBox.prop(tool, "tex_ignore_filter")
1178 | matImportBox.separator()
1179 | matImportBox.label(text="Material settings:")
1180 | matImportBox.prop(tool, "use_fake_user")
1181 | matImportBox.prop(tool, "use_real_displacement")
1182 | matImportBox.prop(tool, "add_extranodes")
1183 | matImportBox.prop(tool, "texture_mapping")
1184 | matImportBox.separator()
1185 | matImportBox.label(text="Import following textures into materials (if found):")
1186 | matImportBox.prop(tool, "import_diff")
1187 | matImportBox.prop(tool, "import_sss")
1188 | matImportBox.prop(tool, "import_met")
1189 | matImportBox.prop(tool, "import_spec")
1190 | matImportBox.prop(tool, "import_rough")
1191 | matImportBox.prop(tool, "import_emission")
1192 | matImportBox.prop(tool, "import_alpha")
1193 | matImportBox.prop(tool, "import_norm")
1194 | matImportBox.prop(tool, "import_disp")
1195 |
1196 |
1197 | # Model import UI
1198 | modelImportBox = layout.box()
1199 | modelImportRow = modelImportBox.row()
1200 | modelImportRow.prop(obj, "modelImport_expanded",
1201 | icon="TRIA_DOWN" if obj.modelImport_expanded else "TRIA_RIGHT",
1202 | icon_only=True, emboss=False
1203 | )
1204 | modelImportRow.label(text="Batch import 3D models")
1205 | if obj.modelImport_expanded:
1206 | modelImportBox.prop(tool, "model_import_path")
1207 | modelImportBox.label(text='Make sure to uncheck "Relative Path"!', icon="ERROR")
1208 | modelImportBox.operator("alt.importmodels")
1209 | modelImportOptionsRow = modelImportBox.row()
1210 | modelImportOptionsRow.prop(obj, "modelImportOptions_expanded",
1211 | icon="TRIA_DOWN" if obj.modelImportOptions_expanded else "TRIA_RIGHT",
1212 | icon_only=True, emboss=False
1213 | )
1214 | modelImportOptionsRow.label(text="Import options: ")
1215 | if obj.modelImportOptions_expanded:
1216 | modelImportOptionsRow = modelImportBox.row()
1217 | modelImportBox.label(text="Model options:")
1218 | modelImportBox.prop(tool, "hide_after_import")
1219 | modelImportBox.prop(tool, "move_to_new_collection_after_import")
1220 | modelImportBox.prop(tool, "join_new_objects")
1221 | modelImportBox.separator()
1222 | modelImportBox.label(text="Search for and import the following filetypes:")
1223 | modelImportBox.prop(tool, "import_fbx")
1224 | modelImportBox.prop(tool, "import_gltf")
1225 | modelImportBox.prop(tool, "import_obj")
1226 | modelImportBox.prop(tool, "import_x3d")
1227 |
1228 |
1229 | # Append from other .blend UI
1230 | appendBox = layout.box()
1231 | appendRow = appendBox.row()
1232 | appendRow.prop(obj, "append_expanded",
1233 | icon="TRIA_DOWN" if obj.append_expanded else "TRIA_RIGHT",
1234 | icon_only=True, emboss=False
1235 | )
1236 | appendRow.label(text="Batch append from .blend files")
1237 | if obj.append_expanded:
1238 | appendBox.prop(tool, "append_path")
1239 | appendBox.label(text='Make sure to uncheck "Relative Path"!', icon="ERROR")
1240 | appendBox.prop(tool, "append_recursive_search")
1241 | appendBox.prop(tool, "append_move_to_new_collection_after_import")
1242 | appendBox.prop(tool, "append_join_new_objects")
1243 | appendBox.prop(tool, "appendType")
1244 | if obj.appendType == 'objects':
1245 | appendBox.prop(tool, "deleteLights")
1246 | appendBox.prop(tool, "deleteCameras")
1247 | appendBox.operator("alt.batchappend")
1248 |
1249 |
1250 | # Asset browser operations UI
1251 | assetBrowserOpsBox = layout.box()
1252 | assetBrowserOpsRow = assetBrowserOpsBox.row()
1253 | assetBrowserOpsRow.prop(obj, "assetBrowserOpsRow_expanded",
1254 | icon="TRIA_DOWN" if obj.assetBrowserOpsRow_expanded else "TRIA_RIGHT",
1255 | icon_only=True, emboss=False
1256 | )
1257 | assetBrowserOpsRow.label(text="Asset browser operations")
1258 | if obj.assetBrowserOpsRow_expanded:
1259 | assetBrowserOpsRow = assetBrowserOpsBox.row()
1260 | assetBrowserOpsBox.label(text="Batch mark/unmark assets:")
1261 | assetBrowserOpsBox.prop(tool, "markunmark")
1262 | assetBrowserOpsBox.prop(tool, "assettype")
1263 | assetBrowserOpsBox.operator("alt.manageassets")
1264 | assetBrowserOpsBox.label(text="Generate asset previews:")
1265 | assetBrowserOpsBox.prop(tool, "previewgentype")
1266 | assetBrowserOpsBox.operator("alt.generateassetpreviews")
1267 |
1268 |
1269 | # Utility operations UI
1270 | utilBox = layout.box()
1271 | utilRow = utilBox.row()
1272 | utilRow.prop(obj, "utilRow_expanded",
1273 | icon="TRIA_DOWN" if obj.utilRow_expanded else "TRIA_RIGHT",
1274 | icon_only=True, emboss=False
1275 | )
1276 | utilRow.label(text="Utilities")
1277 | if obj.utilRow_expanded:
1278 | utilRow = utilBox.row()
1279 | utilBox.prop(tool, "deleteType")
1280 | utilBox.operator("alt.batchdelete")
1281 | utilBox.separator()
1282 | utilBox.label(text='Deletes based on material name, not material contents', icon="ERROR")
1283 | utilBox.operator("alt.simpledeldupemats")
1284 | utilBox.operator("alt.cleanupunusedmats")
1285 | utilBox.separator()
1286 | utilBox.prop(tool, "dispNewScale")
1287 | utilBox.operator("alt.changealldispscale")
1288 | utilBox.operator("alt.userealdispall")
1289 |
1290 |
1291 | #Asset snapshot UI
1292 | snapshotBox = layout.box()
1293 | snapshotRow = snapshotBox.row()
1294 | snapshotRow.prop(obj, "snapshotRow_expanded",
1295 | icon="TRIA_DOWN" if obj.snapshotRow_expanded else "TRIA_RIGHT",
1296 | icon_only=True, emboss=False
1297 | )
1298 | snapshotRow.label(text="Asset snapshot")
1299 | if obj.snapshotRow_expanded:
1300 | snapshotBox.label(text='Sometimes crashes. SAVE YOUR FILES', icon="ERROR")
1301 | snapshotBox.prop(tool, "resolution")
1302 | snapshotBox.operator("view3d.object_preview")
1303 | snapshotBox.operator("view3d.asset_snaphot_collection")
1304 |
1305 |
1306 | # Asset downloader UI
1307 | assetDownloaderBox = layout.box()
1308 | assetDownloaderRow = assetDownloaderBox.row()
1309 | assetDownloaderRow.prop(obj, "assetDownloaderRow_expanded",
1310 | icon="TRIA_DOWN" if obj.assetDownloaderRow_expanded else "TRIA_RIGHT",
1311 | icon_only=True, emboss=False
1312 | )
1313 | assetDownloaderRow.label(text="Batch asset downloader [EXPERIMENTAL]")
1314 | if obj.assetDownloaderRow_expanded:
1315 | assetDownloaderRow = assetDownloaderBox.row()
1316 | assetDownloaderBox.label(text='Downloads files from ambientcg.com')
1317 | assetDownloaderBox.prop(tool, "downloader_save_path")
1318 | assetDownloaderBox.label(text='Make sure to uncheck "Relative Path"!', icon="ERROR")
1319 | assetDownloaderBox.prop(tool, "keywordFilter")
1320 | assetDownloaderBox.prop(tool, "showAllDownloadAttribs")
1321 | assetDownloaderBox.prop(tool, "attributeFilter")
1322 | assetDownloaderBox.prop(tool, "extensionFilter")
1323 | assetDownloaderBox.prop(tool, "unZip")
1324 | assetDownloaderBox.prop(tool, "deleteZips")
1325 | assetDownloaderBox.prop(tool, "skipDuplicates")
1326 | assetDownloaderBox.prop(tool, "terminal")
1327 | assetDownloaderBox.operator("alt.assetdownloader")
1328 |
1329 |
1330 | # SBSAR import UI
1331 | sbsarImportBox = layout.box()
1332 | sbsarImportRow = sbsarImportBox.row()
1333 | sbsarImportRow.prop(obj, "sbsarImport_expanded",
1334 | icon="TRIA_DOWN" if obj.sbsarImport_expanded else "TRIA_RIGHT",
1335 | icon_only=True, emboss=False
1336 | )
1337 | sbsarImportRow.label(text="Batch import SBSAR files [EXPERIMENTAL]")
1338 | if obj.sbsarImport_expanded:
1339 | sbsarImportBox.label(text="Requires adobe substance 3D add-on for Blender", icon="ERROR")
1340 | sbsarImportBox.prop(tool, "sbsar_import_path")
1341 | sbsarImportBox.label(text='Make sure to uncheck "Relative Path"!', icon="ERROR")
1342 | sbsarImportBox.operator("alt.importsbsar")
1343 |
1344 |
1345 | # ------------------------------------------------------------------------
1346 | # Registration
1347 | # ------------------------------------------------------------------------
1348 |
1349 | classes = (
1350 | properties,
1351 | OT_BatchImportPBR,
1352 | OT_ImportModels,
1353 | OT_BatchAppend,
1354 | OT_ManageAssets,
1355 | OT_GenerateAssetPreviews,
1356 | OT_BatchDelete,
1357 | OT_SimpleDelDupeMaterials,
1358 | OT_CleanupUnusedMaterials,
1359 | OT_UseDisplacementOnAll,
1360 | OT_ChangeAllDisplacementScale,
1361 | OT_AssetSnapshotCollection,
1362 | OT_AssetSnapshotObject,
1363 | OT_AssetDownloaderOperator,
1364 | OT_ImportSBSAR,
1365 | OBJECT_PT_panel
1366 | )
1367 |
1368 | def register():
1369 | from bpy.utils import register_class
1370 | for cls in classes:
1371 | register_class(cls)
1372 | bpy.types.Scene.assetlibrarytools = PointerProperty(type=properties)
1373 |
1374 | def unregister():
1375 | from bpy.utils import unregister_class
1376 | for cls in reversed(classes):
1377 | unregister_class(cls)
1378 | del bpy.types.Scene.assetlibrarytools
1379 |
1380 | if __name__ == "__main__":
1381 | register()
1382 |
--------------------------------------------------------------------------------