-
Notifications
You must be signed in to change notification settings - Fork 25
/
prep.py
executable file
·598 lines (512 loc) · 19.4 KB
/
prep.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import os
import bpy
from bpy_extras.io_utils import ImportHelper
from .. import conf
from . import generate
from . import sequences
from .. import tracking
from .. import util
from . import uv_tools
# -----------------------------------------------------------------------------
# Material class functions
# -----------------------------------------------------------------------------
class McprepMaterialProps():
"""Class to inheret reused MCprep settings.
Benefit is to also enforce the same options, required where exec funcitons
pass through from one operator to the other (e.g. prep mats on swap packs)
"""
animateTextures = bpy.props.BoolProperty(
name = "Animate textures (may be slow first time)",
description = ("Swap still images for the animated sequenced found in "
"the active or default texture pack."),
default = False)
autoFindMissingTextures = bpy.props.BoolProperty(
name = "Find missing images",
description = "If the texture for an existing material is missing, try "+\
"to load from the default texture pack instead",
default = True
)
combineMaterials = bpy.props.BoolProperty(
name = "Combine materials",
description = "Consolidate duplciate materials & textures",
default = False
)
improveUiSettings = bpy.props.BoolProperty(
name = "Improve UI",
description = "Automatically improve relevant UI settings",
default = True)
usePrincipledShader = bpy.props.BoolProperty(
name = "Use Principled Shader (if available)",
description = ("If available and using cycles, build materials using the "
"principled shader"),
default = True
)
useReflections = bpy.props.BoolProperty(
name = "Use reflections",
description = "Allow appropriate materials to be rendered reflective",
default = True
)
useExtraMaps = bpy.props.BoolProperty(
name = "Use extra maps",
description = ("load other image passes like normal and "
"spec maps if available"),
default = True
)
normalIntensity = bpy.props.FloatProperty(
name = "Normal map intensity",
description = ("Set normal map intensity, if normal maps are found in "
"the active texture pack and using normal/spec passes"),
default = 1.0,
max=1,
min=0
)
makeSolid = bpy.props.BoolProperty(
name = "Make all materials solid",
description = "Make all materials solid only, for shadows and rendering",
default = False
)
syncMaterials = bpy.props.BoolProperty(
name = "Sync materials",
description = ("Synchronize materials with those in the active "
"pack's materials.blend file"),
default = True
)
packFormat = bpy.props.EnumProperty(
name="Pack Format",
description="Change the pack format when using a PBR resource pack.",
items=[
("specular", "Specular", "Sets the pack format to Specular."),
("seus", "SEUS", "Sets the pack format to SEUS.")],
default="specular"
)
# prop: set all blocks as solid (no transparency), assume has trans, or compute check
def draw_mats_common(self, context):
row = self.layout.row()
col = row.column()
engine = context.scene.render.engine
if engine=='CYCLES' or engine=='BLENDER_EEVEE':
col.prop(self, "packFormat")
col.prop(self, "usePrincipledShader")
col.prop(self, "useReflections")
col.prop(self, "makeSolid")
col.prop(self, "animateTextures")
col.prop(self, "autoFindMissingTextures")
row = self.layout.row()
row.prop(self, "useExtraMaps")
row.prop(self, "syncMaterials")
# col = row.column()
# col.prop(self, "normalIntensity", slider=True)
split = self.layout.split()
row = self.layout.row()
col = row.column()
col.prop(self, "improveUiSettings")
col = row.column()
col.prop(self, "combineMaterials")
class MCPREP_OT_prep_materials(bpy.types.Operator, McprepMaterialProps):
"""Fixes materials and textures on selected objects for Minecraft rendering"""
bl_idname = "mcprep.prep_materials"
bl_label = "MCprep Materials"
bl_options = {'REGISTER', 'UNDO'}
skipUsage = bpy.props.BoolProperty(
default = False,
options = {'HIDDEN'}
)
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self, width=300*util.ui_scale())
def draw(self, context):
draw_mats_common(self, context)
track_function = "materials"
track_param = None
track_exporter = None
@tracking.report_error
def execute(self, context):
# get list of selected objects
obj_list = context.selected_objects
if not obj_list:
if not self.skipUsage:
self.report({'ERROR'}, "No objects selected")
return {'CANCELLED'}
# gets the list of materials (without repetition) from selected
mat_list = util.materialsFromObj(obj_list)
if not mat_list:
if not self.skipUsage:
self.report({'ERROR'}, "No materials found on selected objects")
return {'CANCELLED'}
# check if linked material exists
engine = context.scene.render.engine
count = 0
count_lib_skipped = 0
for mat in mat_list:
if not mat:
conf.log("During prep, found null material:"+str(mat), vv_only=True)
continue
elif mat.library:
count_lib_skipped += 1
continue
passes = generate.get_textures(mat)
if not self.useExtraMaps:
for pass_name in passes:
if pass_name != "diffuse":
passes[pass_name] = None
if self.autoFindMissingTextures:
for pass_name in passes:
res = generate.replace_missing_texture(passes[pass_name])
if res>0:
mat["texture_swapped"] = True # used to apply saturation
if engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
res = generate.matprep_internal(mat, passes,
self.useReflections, self.makeSolid)
if res==0:
count+=1
elif engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
res = generate.matprep_cycles(mat, passes, self.useReflections,
self.usePrincipledShader, self.makeSolid, self.packFormat)
if res==0:
count+=1
else:
self.report({'ERROR'}, "Only Blender Internal, Cycles, or Eevee supported")
return {'CANCELLED'}
if self.animateTextures:
sequences.animate_single_material(
mat, context.scene.render.engine)
if self.syncMaterials is True:
bpy.ops.mcprep.sync_materials(
selected=True, link=False, replace_materials=False, skipUsage=True)
if self.combineMaterials is True:
bpy.ops.mcprep.combine_materials(selection_only=True, skipUsage=True)
if self.improveUiSettings:
bpy.ops.mcprep.improve_ui()
if self.skipUsage is True:
pass # don't report if a meta-call
elif count_lib_skipped > 0:
self.report({"INFO"},
"Modified {} materials, skipped {} linked ones.".format(
count, count_lib_skipped))
elif count >0:
self.report({"INFO"},"Modified "+str(count)+" materials")
else:
self.report({"ERROR"}, "Nothing modified, be sure you selected objects with existing materials!")
addon_prefs = util.get_user_preferences(context)
self.track_param = context.scene.render.engine
self.track_exporter = addon_prefs.MCprep_exporter_type
return {'FINISHED'}
class MCPREP_OT_materials_help(bpy.types.Operator):
"""Follow up popup to assist the user who may not have gotten expected change"""
bl_idname = "mcprep.prep_materials_help"
bl_label = "MCprep Materials Help"
bl_options = {'REGISTER', 'UNDO'}
def update_supress_help(self, context):
"""Update trigger for supressing help popups."""
if conf.v and self.suppress_help:
print("Supressing future help popups")
elif conf.v and not self.suppress_help:
print("Re-enabling popup warnings")
help_num = bpy.props.IntProperty(
default = 0,
options = {'HIDDEN'}
)
suppress_help = bpy.props.BoolProperty(
name = "Don't show this again",
default = False,
options = {'HIDDEN'},
update = update_supress_help
)
def invoke(self, context, event):
# check here whether to trigger popup, based on supression
return context.window_manager.invoke_props_dialog(self, width=400*util.ui_scale())
def draw(self, context):
layout = self.layout
col = layout.column()
if self.help_num == 0:
# No specific error occured
col.scale_y = 0.7
col.label(text="No specific MCprep material issue identified.")
col.label(text="Still need help? Press OK below to open an issue.")
elif self.help_num == 1:
# No materials modified, because no materials detected
col.scale_y = 0.7
col.label(text="Could not prep materials because")
col.label(text="because none of the selected objects")
col.label(text="have materials. Be sure to select the")
col.label(text="model or world import before prepping!")
elif self.help_num == 2:
# Missing SOME textures detected, either because find msising is off
# or if replacement still not found even with setting on
col.scale_y = 0.7
col.label(text="Some materials have missing textures,")
col.label(text="these may show up as pink or black materials")
col.label(text="in the viewport or in a render. Try using:")
col.label(text="file > External Data > Find missing files")
elif self.help_num == 3:
# It worked, but maybe the user isn't seeing what they expect
col.scale_y = 0.7
col.label(text="Material prepping worked, but you might need")
col.label(text="to \"Improve UI\" or go into texture/rendered")
col.label(text="mode (shift+z) to see imrpoved textures")
col.prop(self, "suppress_help")
self.help_num = 0 # reset in event of unset re-trigger
def execute(self, context):
if self.help_num == 0:
bpy.ops.wm.url_open(
url = "")
return {'FINISHED'}
class MCPREP_OT_swap_texture_pack(bpy.types.Operator, ImportHelper, McprepMaterialProps):
"""Swap current textures for that of a texture pack folder"""
bl_idname = "mcprep.swap_texture_pack"
bl_label = "Swap Texture Pack"
bl_description = ("Change the texture pack for all materials of selected objects, "
"select a folder path for an unzipped resource pack or texture folder")
bl_options = {'REGISTER', 'UNDO'}
filter_glob = bpy.props.StringProperty(
default="",
options = {'HIDDEN'}
)
use_filter_folder = True
fileselectparams = "use_filter_blender"
filepath = bpy.props.StringProperty(subtype='DIR_PATH')
filter_image = bpy.props.BoolProperty(
default=True,
options={'HIDDEN', 'SKIP_SAVE'}
)
filter_folder = bpy.props.BoolProperty(
default=True,
options={'HIDDEN', 'SKIP_SAVE'}
)
prepMaterials = bpy.props.BoolProperty(
name = "Prep materials",
description = "Runs prep materials after texture swap to regenerate materials.",
default=False)
skipUsage = bpy.props.BoolProperty(
default = False,
options={'HIDDEN'}
)
@classmethod
def poll(cls, context):
addon_prefs = util.get_user_preferences(context)
return addon_prefs.MCprep_exporter_type != "(choose)"
def draw(self, context):
row = self.layout.row()
col = row.column()
subcol = col.column()
subcol.scale_y = 0.7
subcol.label(text="Select any subfolder of an")
subcol.label(text="unzipped texture pack, then")
subcol.label(text="press 'Swap Texture Pack'")
subcol.label(text="after confirming these")
subcol.label(text="settings below:")
col.prop(self, "useExtraMaps")
col.prop(self, "animateTextures")
col.prop(self, "prepMaterials")
if self.prepMaterials:
col.prop(self, "packFormat")
col.prop(self, "usePrincipledShader")
col.prop(self, "useReflections")
col.prop(self, "autoFindMissingTextures")
col.prop(self, "syncMaterials")
col.prop(self, "improveUiSettings")
col.prop(self, "combineMaterials")
track_function = "texture_pack"
track_param = None
track_exporter = None
@tracking.report_error
def execute(self,context):
addon_prefs = util.get_user_preferences(context)
# check folder exist, but keep relative if relevant
folder = self.filepath
if os.path.isfile(bpy.path.abspath(folder)):
folder = os.path.dirname(folder)
conf.log("Folder: " + folder)
if not os.path.isdir(bpy.path.abspath(folder)):
self.report({'ERROR'}, "Selected folder does not exist")
return {'CANCELLED'}
# get list of selected objects
obj_list = context.selected_objects
if len(obj_list)==0:
self.report({'ERROR'}, "No objects selected")
return {'CANCELLED'}
# gets the list of materials (without repetition) from selected
mat_list = util.materialsFromObj(obj_list)
if len(obj_list)==0:
self.report({'ERROR'}, "No materials found on selected objects")
return {'CANCELLED'}
exporter = generate.detect_form(mat_list)
invalid_uv, affected_objs = uv_tools.detect_invalid_uvs_from_objs(obj_list)
self.track_exporter = addon_prefs.MCprep_exporter_type
# set the scene's folder for the texturepack being swapped
context.scene.mcprep_texturepack_path = folder
conf.log("Materials detected: " + str(len(mat_list)))
res = 0
for mat in mat_list:
self.preprocess_material(mat)
res += generate.set_texture_pack(mat, folder, self.useExtraMaps)
if self.animateTextures:
sequences.animate_single_material(
mat, context.scene.render.engine)
generate.set_saturation_material(mat) # may be a double call if was animated tex
if self.prepMaterials:
bpy.ops.mcprep.prep_materials(
animateTextures = self.animateTextures,
autoFindMissingTextures = self.autoFindMissingTextures,
combineMaterials = self.combineMaterials,
improveUiSettings = self.improveUiSettings,
usePrincipledShader = self.usePrincipledShader,
useReflections = self.useReflections,
useExtraMaps = self.useExtraMaps,
normalIntensity = self.normalIntensity,
makeSolid = self.makeSolid,
syncMaterials = self.syncMaterials,
packFormat = self.packFormat,
skipUsage = True)
if invalid_uv:
self.report({'ERROR'},
("Detected scaled UV's (all in one texture), be sure to use "
"Mineway's 'Export Tiles for textures'"))
conf.log("Detected scaledd UV's, incompatible with swap textures")
conf.log([ob.name for ob in affected_objs], vv_only=True)
else:
self.report({'INFO'},"{} materials affected".format(res))
self.track_param = context.scene.render.engine
return {'FINISHED'}
def preprocess_material(self, material):
"""Preprocess materials for special edge cases"""
# in texture packs, this is actually just a transparent overaly -
# but in Mineways export, this is the flattened grass/drit block side
if material.name == "grass_block_side_overlay":
material.name = "grass_block_side"
conf.log("Renamed material: grass_block_side_overlay to grass_block_side")
class MCPREP_OT_load_material(bpy.types.Operator, McprepMaterialProps):
"""Load the select material from the active resource pack and prep it"""
bl_idname = "mcprep.load_material"
bl_label = "Generate material"
bl_description = ("Generate and apply the selected material based on active "
"resource pack")
bl_options = {'REGISTER', 'UNDO'}
skipUsage = bpy.props.BoolProperty(
default = False,
options={'HIDDEN'}
)
@classmethod
def poll(cls, context):
return context.object and context.scene.mcprep_props.material_list
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self, width=300*util.ui_scale())
def draw(self, context):
draw_mats_common(self, context)
track_function = "generate_mat"
track_param = None
@tracking.report_error
def execute(self, context):
scn_props = context.scene.mcprep_props
mat_item = scn_props.material_list[scn_props.material_list_index]
mat, err = self.generate_base_material(
context, mat_item.name, mat_item.path)
if mat is None and err:
self.report({"ERROR"}, err)
return {'CANCELLED'}
elif mat is None:
self.report({"ERROR"}, "Failed generate base material")
return {'CANCELLED'}
context.object.active_material = mat
# Don't want to generally run prep, as this would affect everything
# selected, as opposed to affecting just the new material
# bpy.ops.mcprep.prep_materials()
# Instead, run the update steps below copied from the MCprep inner loop
res, err = self.update_material(context, mat)
if res is False and err:
self.report({"ERROR"}, err)
return {'CANCELLED'}
elif res is False:
self.report({"ERROR"}, "Failed to prep generated material")
return {'CANCELLED'}
self.track_param = context.scene.render.engine
return {'FINISHED'}
def generate_base_material(self, context, name, path):
"""Generate a base material from name and active resource pack"""
image = bpy.data.images.load(path)
mat = bpy.data.materials.new(name=name)
engine = context.scene.render.engine
if engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
generate.set_internal_texture(image, mat, self.useExtraMaps)
elif engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
# need to create at least one texture node first, then the rest works
mat.use_nodes = True
node_diff = mat.node_tree.nodes.new('ShaderNodeTexImage')
node_diff.image = image
node_diff["MCPREP_diffuse"] = True
# Initialize extra passes as well
node_spec = mat.node_tree.nodes.new('ShaderNodeTexImage')
node_spec["MCPREP_specular"] = True
node_nrm = mat.node_tree.nodes.new('ShaderNodeTexImage')
node_nrm["MCPREP_normal"] = True
conf.log("Added blank texture node")
# now use standard method to update textures
generate.set_cycles_texture(image, mat, self.useExtraMaps)
else:
return None, "Only Blender Internal, Cycles, or Eevee supported"
return mat, None
def update_material(self, context, mat):
"""Update the initially created material"""
if not mat:
conf.log("During prep, found null material:"+str(mat), vv_only=True)
return
elif mat.library:
return
engine = context.scene.render.engine
passes = generate.get_textures(mat)
conf.log("Load Mat Passes:"+str(passes), vv_only=True)
if not self.useExtraMaps:
for pass_name in passes:
if pass_name != "diffuse":
passes[pass_name] = None
if self.autoFindMissingTextures:
for pass_name in passes:
res = generate.replace_missing_texture(passes[pass_name])
if res>0:
mat["texture_swapped"] = True # used to apply saturation
if engine == 'BLENDER_RENDER' or engine == 'BLENDER_GAME':
res = generate.matprep_internal(mat, passes,
self.useReflections, self.makeSolid)
elif engine == 'CYCLES' or engine == 'BLENDER_EEVEE':
res = generate.matprep_cycles(mat, passes, self.useReflections,
self.usePrincipledShader, self.makeSolid, self.packFormat)
else:
return False, "Only Blender Internal, Cycles, or Eevee supported"
success = res==0
if self.animateTextures:
sequences.animate_single_material(
mat, context.scene.render.engine)
return success, None
# -----------------------------------------------------------------------------
# Registration
# -----------------------------------------------------------------------------
classes = (
MCPREP_OT_prep_materials,
MCPREP_OT_materials_help,
MCPREP_OT_swap_texture_pack,
MCPREP_OT_load_material,
)
def register():
util.make_annotations(McprepMaterialProps)
for cls in classes:
util.make_annotations(cls)
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)