-
Notifications
You must be signed in to change notification settings - Fork 2
/
material.py
1841 lines (1531 loc) · 61.9 KB
/
material.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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2016-2019, Thomas Larsson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.
import bpy
from bpy.props import *
import os
import copy
from collections import OrderedDict
from .asset import Asset
from .utils import *
from .settings import theSettings
from .error import *
from mathutils import Vector, Matrix
if bpy.app.version < (2,80,0):
from .buttons27 import SlotString, UseInternalBool, ImageFile, DazImageFile, MultiFile, ResizeOptions, DazChannelFactor
else:
from .buttons28 import SlotString, UseInternalBool, ImageFile, DazImageFile, MultiFile, ResizeOptions, DazChannelFactor
WHITE = Vector((1.0,1.0,1.0))
GREY = Vector((0.5,0.5,0.5))
BLACK = Vector((0.0,0.0,0.0))
#-------------------------------------------------------------
# Materials
#-------------------------------------------------------------
def getMatKey(id):
from .asset import normalizePath
id = normalizePath(id)
key = id.split("#")[-1]
words = key.rsplit("-",1)
if (len(words) == 2 and
words[1].isdigit()):
return words[0]
else:
return key
class Material(Asset):
def __init__(self, fileref):
Asset.__init__(self, fileref)
self.scene = None
self.shader = 'DAZ'
self.channels = OrderedDict()
self.studioChannels = OrderedDict()
self.textures = OrderedDict()
self.groups = []
self.ignore = False
self.shells = []
self.geometry = None
self.geosockets = []
self.uv_set = None
self.uv_sets = {}
self.udim = 0
self.basemix = 0
self.thinWalled = False
self.refractive = False
self.thinGlass = False
self.shareGlossy = False
self.hideMaterial = False
self.metallic = False
self.dualLobeWeight = 0
self.translucent = False
def __repr__(self):
return ("<Material %s %s %s>" % (self.id, self.rna, self.geometry))
def parse(self, struct):
Asset.parse(self, struct)
if "url" in struct.keys():
asset = self.getAsset(struct["url"])
if asset:
self.channels = copy.deepcopy(asset.channels)
self.set(struct)
def update(self, struct):
Asset.update(self, struct)
self.set(struct)
#for grp in struct["groups"]:
# setMaterial(struct["geometry"], grp, self)
if "uv_set" in struct.keys():
from .geometry import Uvset
self.uv_set = self.getTypedAsset(struct["uv_set"], Uvset)
if self.uv_set:
self.uv_set.material = self
if "geometry" in struct.keys():
geo = self.getAsset(struct["geometry"], True)
key = getMatKey(self.id)
if geo is not None:
if key not in geo.materials.keys():
geo.materials[key] = []
geo.materials[key].append(self)
self.geometry = geo
self.basemix = self.getValue(["Base Mixing"], 0)
if self.basemix == 2:
self.basemix = 0
elif self.basemix not in [0,1]:
raise DazError("Unknown Base Mixing: %s " % self.material.basemix)
self.thinWalled = self.getValue(["Thin Walled"], False)
self.refractive = (self.getValue("getChannelRefractionStrength", 0) > 0.01 or
self.getValue("getChannelOpacity", 1) < 0.99)
self.thinGlass = (self.thinWalled and self.refractive)
self.shareGlossy = self.getValue(["Share Glossy Inputs"], False)
self.metallic = (self.getValue(["Metallic Weight"], 0) > 0.5)
self.dualLobeWeight = self.getValue(["Dual Lobe Specular Weight"], 0)
self.translucent = (self.getValue("getChannelTranslucencyWeight", 0) > 0.01)
def set(self, struct):
for key,data in struct.items():
if key == "extra":
for extra in data:
self.setExtra(extra)
elif isinstance(data, dict):
if "channel" in data.keys():
self.replaceChannel(key, data["channel"])
elif "color" in data.keys() or "strength" in data.keys():
self.replaceChannel(key, data)
def setExtra(self, struct):
if (struct["type"] == "studio_material_channels" and
"channels" in struct.keys()):
for elt in struct["channels"]:
data = elt["channel"]
key = data["id"]
self.replaceChannel(key, data)
if "label" in self.channels.keys():
key = data["label"]
self.replaceChannel(key, data)
elif struct["type"] == "studio/material/uber_iray":
self.shader = 'IRAY'
elif struct["type"] == "studio/material/daz_brick":
self.shader = '3DELIGHT'
elif struct["type"] == "studio/material/daz_shader":
self.shader = 'DAZ'
return
if struct["type"] == "studio/material/daz_shader":
if "definition" in struct.keys():
print("DEFINED IN", struct["definition"])
elif "property_settings" in struct.keys():
for prop,value in struct["property_settings"].items():
self.channels[prop] = value
def replaceChannel(self, key, data):
if key in self.channels.keys():
channel = self.channels[key]
for name,value in data.items():
channel[name] = value
else:
self.channels[key] = data
def copyChannels(self, base):
for key,value in base.channels.items():
if key not in self.channels.keys():
self.channels[key] = value.copy()
def build(self, context):
from .asset import normalizePath
from .geometry import Geometry
if self.ignore:
return
if self.rna is None:
self.rna = bpy.data.materials.new(self.name)
scn = self.scene = context.scene
mat = self.rna
mat.DazRenderEngine = scn.render.engine
mat.DazShader = self.shader
if bpy.app.version < (2,80,0):
mat.game_settings.alpha_blend = 'CLIP'
if self.uv_set:
self.uv_sets[self.uv_set.name] = self.uv_set
geo = self.geometry
if geo and isinstance(geo, Geometry):
for uv,uvset in geo.uv_sets.items():
if uvset:
self.uv_sets[uv] = self.uv_sets[uvset.name] = uvset
for shell,uvs in self.shells:
shell.shader = self.shader
if self.thinGlass:
mat.DazThinGlass = True
def postbuild(self, context):
pass
def getUvKey(self, key, struct):
if key in struct.keys():
return key
if key[0:7].lower() == "default":
for key1 in struct.keys():
if key1[0:7].lower() == "default":
print("Alt key: '%s' = '%s'" % (key, key1))
return key1
print("Missing UV for '%s', '%s' not in %s" % (self.name, key, list(struct.keys())))
return key
def getUvSet(self, uv):
key = self.getUvKey(uv, self.uv_sets)
if key is None:
return self.uv_set
elif key not in self.uv_sets.keys():
uvset = Asset(None)
uvset.name = key
self.uv_sets[key] = uvset
return self.uv_sets[key]
def fixUdim(self, udim):
try:
self.rna.DazUDim = udim
except ValueError:
print("UDIM out of range: %d" % udim)
self.rna.DazVDim = 0
addUdim(self.rna, udim, 0)
def fromMaterial(self, mat, ob):
struct = OrderedDict()
struct["id"] = mat.name
self.rna = mat
return struct
def getImageFile(self, channel):
if "image_file" in channel.keys():
return channel["image_file"]
elif "literal_image" in channel.keys():
return channel["literal_image"]
else:
return None
def getGamma(self, channel):
global theGammas
url = self.getImageFile(channel)
gamma = 0
if url in theGammas.keys():
gamma = theGammas[url]
elif "default_image_gamma" in channel.keys():
gamma = channel["default_image_gamma"]
return gamma
#-------------------------------------------------------------
# Get channels
#-------------------------------------------------------------
def getChannelDiffuse(self):
return self.getChannel(["diffuse", "Diffuse Color"])
def getChannelDiffuseStrength(self):
return self.getChannel(["diffuse_strength", "Diffuse Strength"])
def getChannelDiffuseRoughness(self):
return self.getChannel(["Diffuse Roughness"])
def getChannelSpecularColor(self):
return self.getTexChannel(["Glossy Color", "specular", "Specular Color"])
def getChannelSpecularStrength(self):
return self.getTexChannel(["Glossy Layered Weight", "Glossy Weight", "specular_strength", "Specular Strength"])
def getChannelGlossyReflectivity(self):
return self.getChannel(["Glossy Reflectivity"])
def getChannelGlossyRoughness(self):
return self.getChannel(["Glossy Roughness"])
def getChannelGlossySpecular(self):
return self.getChannel(["Glossy Specular"])
def getChannelGlossiness(self):
channel = self.getChannel(["glossiness", "Glossiness"])
if channel:
return channel, False
else:
return self.getChannel(["Glossy Roughness"]), True
def getChannelTranslucencyColor(self):
return self.getChannel(["Translucency Color"])
def getChannelTranslucencyWeight(self):
return self.getChannel(["translucency", "Translucency Weight"])
def getChannelOpacity(self):
return self.getChannel(["opacity"])
def getChannelCutoutOpacity(self):
return self.getChannel(["Cutout Opacity", "transparency"])
def getChannelAmbientColor(self):
return self.getChannel(["ambient", "Ambient Color"])
def getChannelAmbientStrength(self):
return self.getChannel(["ambient_strength", "Ambient Strength"])
def getChannelEmissionColor(self):
return self.getChannel(["emission", "Emission Color"])
def getChannelReflectionColor(self):
return self.getChannel(["reflection", "Reflection Color"])
def getChannelReflectionStrength(self):
return self.getChannel(["reflection_strength", "Reflection Strength"])
def getChannelRefractionColor(self):
return self.getChannel(["refraction", "Refraction Color"])
def getChannelRefractionStrength(self):
return self.getChannel(["refraction_strength", "Refraction Weight"])
def getChannelIOR(self):
return self.getChannel(["ior", "Refraction Index"])
def getChannelSSSColor(self):
return self.getChannel(["Translucency Color", "SSS Color", "Subsurface Color", "SSS Reflectance Tint"])
def getChannelSSSAmount(self):
return self.getChannel(["translucency", "Translucency Weight", "SSS Amount", "Subsurface Strength"])
def getChannelSSSScale(self):
return self.getChannel(["SSS Scale", "Subsurface Scale"])
def getChannelSSSRadius(self):
return self.getChannel(["Scattering Measurement Distance"])
def getChannelSSSIOR(self):
return self.getChannel(["Subsurface Refraction"])
def getChannelTopCoatRoughness(self):
return self.getChannel(["Top Coat Roughness"])
def getChannelNormal(self):
return self.getChannel(["normal", "Normal Map"])
def getChannelBump(self):
return self.getChannel(["bump", "Bump Strength"])
def getChannelBumpMin(self):
return self.getChannel(["bump_min", "Bump Minimum", "Negative Bump"])
def getChannelBumpMax(self):
return self.getChannel(["bump_max", "Bump Maximum", "Positive Bump"])
def getChannelDisplacement(self):
return self.getChannel(["displacement", "Displacement Strength"])
def getChannelDispMin(self):
return self.getChannel(["displacement_min", "Displacement Minimum", "Minimum Displacement"])
def getChannelDispMax(self):
return self.getChannel(["displacement_max", "Displacement Maximum", "Maximum Displacement"])
def getChannelHorizontalTiles(self):
return self.getChannel(["u_scale", "Horizontal Tiles"])
def getChannelHorizontalOffset(self):
return self.getChannel(["u_offset", "Horizontal Offset"])
def getChannelVerticalTiles(self):
return self.getChannel(["v_scale", "Vertical Tiles"])
def getChannelVerticalOffset(self):
return self.getChannel(["v_offset", "Vertical Offset"])
def isActive(self, name):
cname = "%s Active" % name
if cname in self.channels.keys():
channel = self.channels[cname]
if "current_value" in channel.keys():
return channel["current_value"]
elif "value" in channel.keys():
return channel["value"]
return True
def getValue(self, attr, default):
return self.getChannelValue(self.getChannel(attr), default)
def getChannel(self, attr):
if isinstance(attr, str):
return getattr(self, attr)()
for key in attr:
if key in self.channels.keys():
channel = self.channels[key]
if ("visible" not in channel.keys() or
channel["visible"]):
return channel
return None
def getTexChannel(self, channels):
for key in channels:
channel = self.getChannel([key])
if channel and self.hasTextures(channel):
return channel
return self.getChannel(channels)
def hasTexChannel(self, channels):
for key in channels:
channel = self.getChannel([key])
if channel and self.hasTextures(channel):
return True
return False
def getChannelValue(self, channel, default, warn=True):
if channel is None:
return default
if (not self.getImageFile(channel) and
"invalid_without_map" in channel.keys() and
channel["invalid_without_map"]):
return default
for key in ["color", "strength", "current_value", "value"]:
if key in channel.keys():
value = channel[key]
if isVector(default):
if isVector(value):
return value
else:
return Vector((value, value, value))
else:
if isVector(value):
return (value[0] + value[1] + value[2])/3
else:
return value
if warn and theSettings.verbosity > 2:
print("Did not find value for channel %s" % channel["id"])
print("Keys: %s" % list(channel.keys()))
return default
def getChannelColor(self, channel, default, warn=True):
color = self.getChannelValue(channel, default, warn)
if isinstance(color, int) or isinstance(color, float):
color = (color, color, color)
return self.srgbToLinear(color)
def srgbToLinear(self, srgb):
lin = []
for s in srgb:
if s < 0.04045:
l = s/12.92
else:
l = ((s+0.055)/1.055)**2.4
lin.append(l)
return Vector(lin)
def getTextures(self, channel):
if isinstance(channel, tuple):
channel = channel[0]
if channel is None:
return [],[]
elif "image" in channel.keys():
if channel["image"] is None:
return [],[]
else:
maps = self.getAsset(channel["image"]).maps
if maps is None:
maps = []
elif "image_file" in channel.keys():
map = Map({}, False)
map.url = channel["image_file"]
maps = [map]
elif "map" in channel.keys():
maps = Maps(self.fileref)
maps.parse(channel["map"])
halt
elif "literal_image" in channel.keys():
map = Map(channel, False)
map.image = channel["literal_image"]
maps = [map]
elif "literal_maps" in channel.keys():
maps = []
for struct in channel["literal_maps"]["map"]:
if "mask" in struct.keys():
mask = Map(struct["mask"], True)
maps.append(mask)
map = Map(struct, False)
maps.append(map)
else:
return [],[]
texs = []
nmaps = []
for map in maps:
if map.url:
tex = map.getTexture()
elif map.literal_image:
tex = Texture(map)
tex.image = map.literal_image
else:
tex = None
if tex:
texs.append(tex)
nmaps.append(map)
return texs,nmaps
def hasTextures(self, channel):
return (self.getTextures(channel)[0] != [])
def hasAnyTexture(self):
for key in self.channels:
channel = self.getChannel([key])
if self.getTextures(channel)[0]:
return True
return False
def dumpChannels(self):
for key,channel in self.channels.items():
string = ("%s %s %s " % (key, channel["value"], channel["current_value"]))
if "image_file" in channel.keys():
string += channel["image_file"]
print(string)
def sssActive(self):
if not (self.isActive("Subsurface") and theSettings.useSSS):
return False
if self.thinWalled:
return False
return True
#-------------------------------------------------------------
# Textures
#-------------------------------------------------------------
def getRenderMaterial(struct, base):
from .cycles import CyclesMaterial
from .internal import InternalMaterial
if isinstance(base, CyclesMaterial):
return CyclesMaterial
elif isinstance(base, InternalMaterial):
return InternalMaterial
if theSettings.renderMethod in ['BLENDER_RENDER', 'BLENDER_GAME']:
return InternalMaterial
else:
return CyclesMaterial
#-------------------------------------------------------------
# Textures
#-------------------------------------------------------------
class Map:
def __init__(self, map, ismask):
self.url = None
self.label = None
self.operation = "alpha_blend"
self.color = (1,1,1)
self.ismask = ismask
self.image = None
self.size = None
for key,default in [
("url", None),
("color", BLACK),
("label", None),
("operation", "alpha_blend"),
("literal_image", None),
("invert", False),
("transparency", 1),
("rotation", 0),
("xmirror", False),
("ymirror", False),
("xscale", 1),
("yscale", 1),
("xoffset", 0),
("yoffset", 0)]:
if key in map.keys():
setattr(self, key, map[key])
else:
setattr(self, key, default)
def __repr__(self):
return ("<Map %s %s %s (%s %s)>" % (self.image, self.ismask, self.size, self.xoffset, self.yoffset))
def getTexture(self):
global theTextures
if self.url in theTextures.keys():
return theTextures[self.url]
else:
tex = Texture(self)
if self.url:
theTextures[self.url] = tex
return tex
def build(self):
global theImages
if self.image:
return self.image
elif self.url:
if self.url in theImages.keys():
self.image = theImages[self.url]
else:
self.image = loadImage(self.url)
return self.image
else:
return self
def loadImage(url):
from .asset import getDazPath
global theImages
filepath = getDazPath(url)
if filepath is None:
img = None
if theSettings.verbosity > 2:
print('Image not found: \n"%s"' % filepath)
else:
img = bpy.data.images.load(filepath)
img.name = os.path.splitext(os.path.basename(filepath))[0]
theImages[url] = img
return img
class Images(Asset):
def __init__(self, fileref):
Asset.__init__(self, fileref)
self.maps = []
def __repr__(self):
return ("<Images %s r: %s>" % (self.id, self.maps))
def parse(self, struct):
Asset.parse(self, struct)
mapSize = None
for key in struct.keys():
if key == "map":
for mstruct in struct["map"]:
if "mask" in mstruct.keys():
self.maps.append(Map(mstruct["mask"], True))
self.maps.append(Map(mstruct, False))
elif key == "map_size":
mapSize = struct[key]
if mapSize is not None:
for map in self.maps:
map.size = mapSize
self.parseGamma(struct)
def update(self, struct):
self.parseGamma(struct)
def parseGamma(self, struct):
global theGammas
if "map_gamma" in struct.keys():
gamma = struct["map_gamma"]
for map in self.maps:
theGammas[map.url] = gamma
def build(self):
images = []
for map in self.maps:
img = map.build()
images.append(img)
return images
def setImageColorSpace(img, colorspace):
try:
img.colorspace_settings.name = colorspace
return
except TypeError:
pass
alternatives = {
"sRGB" : ["sRGB OETF"],
"Non-Color" : ["Non-Colour Data"],
}
for alt in alternatives[colorspace]:
try:
img.colorspace_settings.name = alt
return
except TypeError:
pass
class Texture:
def __init__(self, map):
self.rna = None
self.map = map
self.built = {"COLOR":False, "NONE":False}
self.images = {"COLOR":None, "NONE":None}
def __repr__(self):
return ("<Texture %s %s %s>" % (self.map.url, self.map.image, self.image))
def buildInternal(self):
global theTextures
if self.built["COLOR"]:
return self
if self.map.url:
key = self.map.url
elif self.map.image:
key = self.map.image.name
else:
key = None
if key is not None:
img = self.images["COLOR"] = self.map.build()
if img:
tex = self.rna = bpy.data.textures.new(img.name, 'IMAGE')
tex.image = img
else:
tex = None
theTextures[key] = self
else:
tex = self.rna = bpy.data.textures.new(self.map.label, 'BLEND')
tex.use_color_ramp = True
r,g,b = self.map.color
for elt in tex.color_ramp.elements:
elt.color = (r,g,b,1)
self.built["COLOR"] = True
return self
def buildCycles(self, colorSpace):
if self.built[colorSpace]:
return self.images[colorSpace]
elif colorSpace == "COLOR" and self.images["NONE"]:
img = self.images["NONE"].copy()
elif colorSpace == "NONE" and self.images["COLOR"]:
img = self.images["COLOR"].copy()
elif self.map.url:
img = self.map.build()
elif self.map.image:
img = self.map.image
else:
img = None
if hasattr(img, "colorspace_settings"):
if colorSpace == "COLOR":
img.colorspace_settings.name = "sRGB"
elif colorSpace == "NONE":
img.colorspace_settings.name = "Non-Color"
else:
img.colorspace_settings.name = colorSpace
if img:
self.images[colorSpace] = img
self.built[colorSpace] = True
return img
def hasMapping(self, map):
if map:
return (map.size is not None)
else:
return (self.map and self.map.size is not None)
def getMapping(self, mat, map):
# mapping scale x = texture width / lie document size x * (lie x scale / 100)
# mapping scale y = texture height / lie document size y * (lie y scale / 100)
# mapping location x = udim place + lie x position * (lie y scale / 100) / lie document size x
# mapping location y = (lie document size y - texture height * (lie y scale / 100) - lie y position) / lie document size y
if self.images["COLOR"]:
img = self.images["COLOR"]
elif self.images["NONE"]:
img = self.images["NONE"]
else:
raise RuntimeError("BUG: getMapping finds no image")
tx,ty = img.size
mx,my = map.size
kx,ky = tx/mx,ty/my
ox,oy = map.xoffset/mx, map.yoffset/my
rz = map.rotation
ox += mat.getChannelValue(mat.getChannelHorizontalOffset(), 0)
oy += mat.getChannelValue(mat.getChannelVerticalOffset(), 0)
kx *= mat.getChannelValue(mat.getChannelHorizontalTiles(), 1)
ky *= mat.getChannelValue(mat.getChannelVerticalTiles(), 1)
sx = map.xscale*kx
sy = map.yscale*ky
if rz == 0:
dx = ox
dy = 1 - sy - oy
if map.xmirror:
dx = sx + ox
sx = -sx
if map.ymirror:
dy = 1 - oy
sy = -sy
elif rz == 90:
dx = ox
dy = 1 - oy
if map.xmirror:
dy = 1 - sy - oy
sy = -sy
if map.ymirror:
dx = sx + ox
sx = -sx
tmp = sx
sx = sy
sy = tmp
rz = 270*D
elif rz == 180:
dx = sx + ox
dy = 1 - oy
if map.xmirror:
dx = ox
sx = -sx
if map.ymirror:
dy = 1 - sy - oy
sy = -sy
rz = 180*D
elif rz == 270:
dx = sx + ox
dy = 1 - sy - oy
if map.xmirror:
dy = 1 - oy
sy = -sy
if map.ymirror:
dx = ox
sx = -sx
tmp = sx
sx = sy
sy = tmp
rz = 90*D
return (dx,dy,sx,sy,rz)
def addUdim(mat, udim, vdim):
if mat.node_tree:
addUdimTree(mat.node_tree, udim, vdim)
else:
for mtex in mat.texture_slots:
if mtex and mtex.texture and mtex.texture.extension == 'CLIP':
mtex.offset[0] += udim
mtex.offset[1] += vdim
def addUdimTree(tree, udim, vdim):
for node in tree.nodes:
if node.type == 'MAPPING':
if hasattr(node, "translation"):
slot = node.translation
else:
slot = node.inputs["Location"].default_value
slot[0] += udim
slot[1] += vdim
elif node.type == 'GROUP':
addUdimTree(node.node_tree, udim, vdim)
#-------------------------------------------------------------z
#
#-------------------------------------------------------------
def clearMaterials():
global theImages, theTextures, theGammas
theImages = {}
theTextures = {}
theGammas = {}
clearMaterials()
def isWhite(color):
return (tuple(color[0:3]) == (1.0,1.0,1.0))
def isBlack(color):
return (tuple(color[0:3]) == (0.0,0.0,0.0))
#-------------------------------------------------------------
# Save local textures
#-------------------------------------------------------------
def saveLocalTextureCopies(context):
from shutil import copyfile
if not bpy.data.filepath:
raise DazError("Save the blend file first")
texpath = os.path.join(os.path.dirname(bpy.data.filepath), "textures")
print("Save textures to '%s'" % texpath)
if not os.path.exists(texpath):
os.makedirs(texpath)
images = []
for ob in getSceneObjects(context):
if ob.type == 'MESH':
for mat in ob.data.materials:
if mat and mat.use_nodes:
saveNodesInTree(mat.node_tree, images)
elif mat:
for mtex in mat.texture_slots:
if mtex:
tex = mtex.texture
if hasattr(tex, "image") and tex.image:
images.append(tex.image)
for img in images:
src = bpy.path.abspath(img.filepath)
src = bpy.path.reduce_dirs([src])[0]
trg = os.path.join(texpath, bpy.path.basename(src))
if src != trg and not os.path.exists(trg):
print("Copy %s\n => %s" % (src, trg))
copyfile(src, trg)
img.filepath = bpy.path.relpath(trg)
def saveNodesInTree(tree, images):
for node in tree.nodes.values():
if node.type == 'TEX_IMAGE':
images.append(node.image)
elif node.type == 'GROUP':
saveNodesInTree(node.node_tree, images)
class DAZ_OT_SaveLocalTextures(bpy.types.Operator):
bl_idname = "daz.save_local_textures"
bl_label = "Save Local Textures"
bl_description = "Copy textures to the textures subfolder in the blend file's directory"
bl_options = {'UNDO'}
@classmethod
def poll(self, context):
return context.object
def execute(self, context):
try:
saveLocalTextureCopies(context)
except DazError:
handleDazError(context)
return{'FINISHED'}
#-------------------------------------------------------------
# Merge identical materials
#-------------------------------------------------------------
def mergeMaterials(ob):
if ob.type != 'MESH':
return
matlist = []
assoc = {}
reindex = {}
m = 0
reduced = False
for n,mat1 in enumerate(ob.data.materials):
unique = True