-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlumiere_beta.py
7167 lines (5961 loc) · 319 KB
/
lumiere_beta.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
# -*- coding:utf-8 -*-
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Lumiere : Blender addon for Blender 3D
# Copyright (C) 2017 Cédric Brandin
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENCE BLOCK *****
bl_info = {
"name": "Lumiere",
"author": "Cédric Brandin (Clarkx)",
"version": (0, 0, 9),
"blender": (2, 76, 3),
"location": "View3D",
"description": "Interactive Lighting Add-on",
"warning": "Beta version",
"wiki_url": "https://github.com/clarkx/Lumiere/wiki",
"tracker_url": "https://github.com/clarkx/Lumiere/issues",
"category": "Render"}
import bpy, bgl, os, blf
from bpy_extras import view3d_utils
from mathutils import Vector, Matrix, Quaternion, Euler
from bpy.types import PropertyGroup, UIList, Panel, Operator
from bpy.props import IntProperty, FloatProperty, BoolProperty, FloatVectorProperty, EnumProperty, StringProperty, CollectionProperty, PointerProperty
from bpy_extras.object_utils import AddObjectHelper, object_data_add
from collections import defaultdict, Counter
from bpy_extras.view3d_utils import location_3d_to_region_2d
import textwrap
import math
import bmesh
import time
import json
#########################################################################################################
#########################################################################################################
def update_panel(self, context):
"""Update the UI panel of the addon from the preferences"""
try:
bpy.utils.unregister_class(LumierePreferences)
except:
pass
LumierePreferences.bl_category = context.user_preferences.addons[__name__].preferences.category
bpy.utils.register_class(LumierePreferences)
#########################################################################################################
#########################################################################################################
class LumierePrefs(bpy.types.AddonPreferences):
"""Preferences of the keymap for the interactive mode"""
bl_idname = __name__
#Align the light based on the view reflection or the normal of the target object
bpy.types.Scene.Key_Normal = StringProperty(
name="View",
description="Align the light with the Reflection or the Normal",
maxlen=1,
default="N")
#Rotate the light on the Z axis
bpy.types.Scene.Key_Rotate = StringProperty(
name="Rotate",
description="Rotate the light on the Z axis",
maxlen=1,
default="R")
#Change the type of the falloff
bpy.types.Scene.Key_Falloff = StringProperty(
name="Falloff",
description="Change the Falloff type of the light",
maxlen=1,
default="F")
#Scale the light on X and Y axis
bpy.types.Scene.Key_Scale = StringProperty(
name="Scale",
description="Scale the light on the Y axis",
maxlen=1,
default="S")
#Scale the light on Y axis
bpy.types.Scene.Key_Scale_Y = StringProperty(
name="Scale Y",
description="Scale the light on the Y axis",
maxlen=1,
default="Z")
#Scale the light on X axis
bpy.types.Scene.Key_Scale_X = StringProperty(
name="Scale X",
description="Scale the light on the X axis",
maxlen=1,
default="X")
#Orbit mode
bpy.types.Scene.Key_Orbit = StringProperty(
name="Orbit",
description="Orbit mode",
maxlen=1,
default="G")
#Distance of the light
bpy.types.Scene.Key_Distance = EnumProperty(name="Distance",
description="Distance from the target object to the light",
items=(
("shift", "shift", "shift", 1),
("alt", "alt", "alt", 2),
("ctrl", "ctrl", "ctrl", 3),
),
default="alt")
#Energy of the light
bpy.types.Scene.Key_Strength = StringProperty(
name="Energy",
description="Energy of the light",
maxlen=1,
default="E")
#Invert the direction of the light
bpy.types.Scene.Key_Invert = StringProperty(
name="Invert",
description="Invert the direction of the light",
maxlen=1,
default="I")
#Grid Gap
bpy.types.Scene.Key_Gap = EnumProperty(name="Grid Gap",
description="Grid Gap",
items=(
("shift", "shift", "shift", 1),
("alt", "alt", "alt", 2),
("ctrl", "ctrl", "ctrl", 3),
),
default="shift")
#HUD Color
bpy.types.Scene.HUD_color = FloatVectorProperty(
name = "",
subtype = "COLOR",
size = 4,
min = 0.0,
max = 1.0,
default = (1.0, 0.09, 0.3, 0.8))
category = bpy.props.StringProperty(
name="Category",
description="Choose a name for the category of the panel",
default="Lumiere",
update=update_panel,
)
def draw(self, context):
scene = context.scene
layout = self.layout
row = layout.row()
row.prop(scene, "Key_Normal")
row.prop(scene, "Key_Rotate")
row.prop(scene, "Key_Falloff")
row = layout.row()
row.prop(scene, "Key_Scale")
row.prop(scene, "Key_Scale_Y")
row.prop(scene, "Key_Scale_X")
row = layout.row()
row.prop(scene, "Key_Orbit")
row.prop(scene, "Key_Distance")
row.prop(scene, "Key_Strength")
row = layout.row()
row.prop(scene, "Key_Invert")
row.prop(scene, "Key_Gap")
row.prop(self, "category")
row = layout.row()
row.prop(scene, "HUD_color", text="HUD Color")
# split = row.split(0.5, align=False)
# split.prop(self, "category")
# split.prop(scene, "HUD_color", text="HUD Color")
#########################################################################################################
#########################################################################################################
def draw_text(color, font_id, left, height, text):
"""Display the differents informations in the interactive mode"""
bgl.glColor4f(*color)
blf.enable(font_id,blf.SHADOW)
blf.shadow(font_id, 5, color[0]-.5, color[1]-.5, color[2]-.5, color[3]-.5) # blur_size being 0 means colored Font, 3 or 5 means a colored rim around the font.# Note that you can only use (0, 3, 5).
blf.shadow_offset(font_id,0,0)
blf.position(font_id, left, height, 0)
blf.draw(font_id, text)
blf.disable(font_id,blf.SHADOW)
def draw_line(x, y, color, width, text_width):
"""Draw a simple line to separate the informations"""
bgl.glLineWidth(width)
bgl.glColor4f(*color)
bgl.glEnable(bgl.GL_BLEND)
bgl.glBegin(bgl.GL_LINES)
bgl.glVertex2f(x, y)
bgl.glVertex2f(x+text_width, y)
bgl.glEnd()
bgl.glLineWidth(1)
def draw_circle_2d(color, cx, cy, r):
"""Draw a circle in bgl for HUD"""
#http://slabode.exofire.net/circle_draw.shtml
num_segments = 4
if num_segments < 1:
num_segments = 1
theta = 2 * 3.1415926 / num_segments
c = math.cos(theta)
s = math.sin(theta)
x = r
y = 0
bgl.glColor4f(*color)
bgl.glEnable(bgl.GL_LINE_SMOOTH)
bgl.glBegin(bgl.GL_LINE_LOOP)
for i in range (num_segments):
bgl.glVertex2f(x + cx, y + cy)
t = x
x = c * x - s * y
y = s * t + c * y
bgl.glEnd()
def draw_bounding_box(context, softbox, matrix, c):
"""Draw the bounding bow of object in bgl"""
bgl.glEnable(bgl.GL_BLEND)
bgl.glColor4f(c[0], c[1], c[2], 0.4)
bgl.glLineWidth(5)
bbox_mat = [matrix * Vector(b) for b in softbox.bound_box]
bbox = [location_3d_to_region_2d(context.region, context.space_data.region_3d, b) for b in bbox_mat]
# bgl.glDisable(bgl.GL_DEPTH_TEST)
bgl.glBegin(bgl.GL_LINE_STRIP)
bgl.glVertex2f(*bbox[0])
bgl.glVertex2f(*bbox[1])
bgl.glVertex2f(*bbox[2])
bgl.glVertex2f(*bbox[3])
bgl.glVertex2f(*bbox[0])
bgl.glVertex2f(*bbox[4])
bgl.glVertex2f(*bbox[5])
bgl.glVertex2f(*bbox[6])
bgl.glVertex2f(*bbox[7])
bgl.glVertex2f(*bbox[4])
bgl.glEnd()
bgl.glBegin(bgl.GL_LINES)
bgl.glVertex2f(*bbox[1])
bgl.glVertex2f(*bbox[5])
bgl.glVertex2f(*bbox[2])
bgl.glVertex2f(*bbox[6])
bgl.glVertex2f(*bbox[3])
bgl.glVertex2f(*bbox[7])
bgl.glEnd()
def draw_callback_px(self, context, event):
"""Display and draw bgl informations"""
obj_light = context.active_object
txt_add_light = "Add light: CTRL+LMB"
region = context.region
lw = 4 // 2
hudcol = context.scene.HUD_color[0], context.scene.HUD_color[1], context.scene.HUD_color[2], context.scene.HUD_color[3]
bgl.glColor4f(*hudcol)
left = 20
#---Region overlap on
overlap = bpy.context.user_preferences.system.use_region_overlap
t_panel_width = 0
if context.area == self.lumiere_area :
if overlap:
for region in bpy.context.area.regions:
if region.type == 'TOOLS':
left += region.width
#---Draw frame around the view3D
bgl.glEnable(bgl.GL_BLEND)
bgl.glLineWidth(4)
bgl.glBegin(bgl.GL_LINE_STRIP)
bgl.glVertex2i(lw, lw)
bgl.glVertex2i(region.width - lw, lw)
bgl.glVertex2i(region.width - lw, region.height - lw)
bgl.glVertex2i(lw, region.height - lw)
bgl.glVertex2i(lw, lw)
bgl.glEnd()
#---Text attribute
font_id = 0
blf.size(font_id, 20, 72)
#---Create light mode
if not self.editmode:
draw_text(hudcol, font_id, left, region.height-55, txt_add_light)
#---Interactive mode
if self.editmode:
#---Interactive mode
if obj_light is not None and obj_light.type != 'EMPTY' and obj_light.data.name.startswith("Lumiere"):
softbox = get_lamp(context, obj_light.Lumiere.lightname)
#---Draw bounding box
# if obj_light.Lumiere.typlight == "Panel":
# matrix = softbox.matrix_world
# color = obj_light.Lumiere.lightcolor
# draw_bounding_box(context, softbox, matrix, color)
# elif obj_light.Lumiere.typlight in ("Area", "Spot", "Point", "Sun"):
#---Draw circle
# bgl.glLineWidth(5)
# color = obj_light.Lumiere.lightcolor
# location = location_3d_to_region_2d(context.region, context.space_data.region_3d, obj_light.matrix_world.translation)
# draw_circle_2d((color[0], color[1], color[2], 0.4), location[0], location[1], 20)
#---Light Name
txt_light_name = "| Light: " + obj_light.name
txt_to_draw = self.reflect_angle + txt_light_name
draw_text(hudcol, font_id, left, region.height-55, txt_to_draw)
#---Draw a line
text_width, text_height = blf.dimensions(font_id, txt_to_draw)
draw_line(left, region.height-62, hudcol, 2, text_width)
#---Keys
key_height = region.height-82
lamp_name = "LAMP_" + obj_light.data.name
if obj_light.Lumiere.typlight == "Env":
txt_rotation = "Rotation: " + str(round(float(obj_light.Lumiere.hdri_rotation),2))
draw_text(hudcol, font_id, left, key_height, txt_rotation)
else:
if self.strength_light:
txt_strength = "Energy: " + str(round(obj_light.Lumiere.energy,3))
draw_text(hudcol, font_id, left, key_height, txt_strength)
elif self.orbit:
txt_orbit = "Orbit mode"
draw_text(hudcol, font_id, left, key_height, txt_orbit)
elif self.dist_light:
txt_range = "Range: " + str(round(obj_light.Lumiere.range,3))
draw_text(hudcol, font_id, left, key_height, txt_range)
elif self.rotate_light_x:
txt_rotation = "Rotation X: " + str(round(math.degrees(obj_light.rotation_euler.x),3))
draw_text(hudcol, font_id, left, key_height, txt_rotation)
elif self.rotate_light_y:
txt_rotation = "Rotation Y: " + str(round(math.degrees(obj_light.rotation_euler.y),3))
draw_text(hudcol, font_id, left, key_height, txt_rotation)
elif self.rotate_light_z:
txt_rotation = "Rotation Z: " + str(round(math.degrees(obj_light.rotation_euler.z),3))
draw_text(hudcol, font_id, left, key_height, txt_rotation)
elif self.falloff_mode :
if (time.time() < (self.key_start + 0.5)):
if obj_light.Lumiere.typfalloff == "0":
draw_text(hudcol, font_id, left, key_height, "Quadratic Falloff")
elif obj_light.Lumiere.typfalloff == "1":
draw_text(hudcol, font_id, left, key_height, "Linear Falloff")
elif obj_light.Lumiere.typfalloff == "2":
draw_text(hudcol, font_id, left, key_height, "Constant Falloff")
else:
self.falloff_mode = False
elif self.scale_light:
if obj_light.Lumiere.typlight == "Spot" :
txt_scale = "Size: " + str(round(math.degrees(bpy.data.lamps[lamp_name].spot_size),3))
elif obj_light.Lumiere.typlight == "Area" :
txt_scale = "Size: " + str(round( (obj_light.scale[0] + obj_light.scale[1]) / 2, 3))
elif obj_light.Lumiere.typlight == "Point":
txt_scale = "Soft shadow size: " + str(round(bpy.data.lamps[lamp_name].shadow_soft_size,3))
elif obj_light.Lumiere.typlight in ("Sun", "Sky"):
txt_scale = "Soft shadow size: " + str(round(bpy.data.lamps[lamp_name].shadow_soft_size,3))
else:
txt_scale = "Scale: " + str(round( (softbox.scale[0] + softbox.scale[1]) / 2, 3))
draw_text(hudcol, font_id, left, key_height, txt_scale)
elif self.scale_light_x:
if obj_light.Lumiere.typlight == "Spot" :
txt_scale = "Shadow size: " + str(round(bpy.data.lamps[lamp_name].shadow_soft_size,3))
elif obj_light.Lumiere.typlight == "Area" :
txt_scale = "Size X: " + str(round(obj_light.scale[0], 3))
elif obj_light.Lumiere.typlight == "Panel":
txt_scale = "Scale X: " + str(round(softbox.scale[0], 3))
draw_text(hudcol, font_id, left, key_height, txt_scale)
elif self.scale_light_y:
if obj_light.Lumiere.typlight == "Spot" :
txt_scale = "Blend: " + str(round(bpy.data.lamps[lamp_name].spot_blend,3))
elif obj_light.Lumiere.typlight == "Area" :
txt_scale = "Size Y: " + str(round(obj_light.scale[1], 3))
elif obj_light.Lumiere.typlight == "Panel":
txt_scale = "Scale Y: " + str(round(softbox.scale[1], 3))
draw_text(hudcol, font_id, left, key_height, txt_scale)
elif self.scale_gapx:
txt_scale = "Gap X: " + str(round(obj_light.Lumiere.gapx, 3))
draw_text(hudcol, font_id, left, key_height, txt_scale)
elif self.scale_gapy:
txt_scale = "Gap Y: " + str(round(obj_light.Lumiere.gapy, 3))
draw_text(hudcol, font_id, left, key_height, txt_scale)
#---Restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
#########################################################################################################
#########################################################################################################
def draw_target_ob(self, context, event):
"""Get the targeted object with object_picker() and draw the name in BGL """
color=(.033, .033, .033, 0.3)
bgl.glEnable(bgl.GL_BLEND)
bgl.glColor4f(*color)
x, y = self.mouse_path
font_id = 0
blf.size(font_id, 15, 72)
w, h, t = (25, 2, 5)
line_height = (blf.dimensions(font_id, "M")[1] * 1.45)
#---Get the name of the object
self.picker = object_picker(self, context, self.mouse_path)
if self.picker is not None:
if bpy.data.objects[self.picker].data.name.startswith("Lumiere"):
color=(.231, .13, .13, .8)
bgl.glColor4f(*color)
text_width, text_height = blf.dimensions(font_id, "No light as target")
else:
text_width, text_height = blf.dimensions(font_id, self.picker)
#Draw rectangle
bgl.glBegin(bgl.GL_QUADS)
bgl.glVertex2f(x+w+t+text_width+t, y+t+line_height)
bgl.glVertex2f(x+w, y+t+line_height)
bgl.glVertex2f(x+w, y)
bgl.glVertex2f(x+w+t+text_width+t, y)
bgl.glEnd()
color=(1, 1, 1, 1.0)
bgl.glColor4f(*color)
blf.position(font_id, x+w+t, y+t, 0)
if bpy.data.objects[self.picker].data.name.startswith("Lumiere"):
blf.draw(font_id, "No light as target")
else:
blf.draw(font_id, self.picker)
#---Restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
#########################################################################################################
#########################################################################################################
def draw_target_px(self, context, event):
"""Get the brightest pixel """
if context.area == self.lumiere_area :
uv_x, uv_y = self.mouse_path
x, y = (event.mouse_x - self.view_3d_region_x[0], event.mouse_y)
#---Draw stippled lines
bgl.glLineStipple(4, 0x5555)
bgl.glEnable(bgl.GL_LINE_STIPPLE)
bgl.glEnable(bgl.GL_BLEND)
hudcol = context.scene.HUD_color
bgl.glColor4f(hudcol[0], hudcol[1], hudcol[2], hudcol[3])
bgl.glLineWidth(4)
bgl.glBegin(bgl.GL_LINE_STRIP)
bgl.glVertex2f(x,0)
bgl.glVertex2f(x,self.img_size_y)
bgl.glEnd()
#---Restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
#########################################################################################################
#########################################################################################################
def object_picker(self, context, coord):
"""Return the name of the object under the eyedropper by ray_cast"""
scene = context.scene
region = context.region
rv3d = context.region_data
ray_max = 10000
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
ray_target = (view_vector * ray_max) - ray_origin
success, location, normal, index, object, matrix = scene.ray_cast(ray_origin, ray_target)
if success:
return(object.name)
else:
return(None)
#########################################################################################################
#########################################################################################################
def get_mat_name(light):
"""Return the name of the material of the light"""
mat_name = "Mat_" + light
mat = bpy.data.materials.get(mat_name)
return(mat_name, mat)
#########################################################################################################
#########################################################################################################
def target_constraint(self, context, name):
"""Add an empty on the target point to constraint the orbit mode"""
obj_light = context.object
empty = bpy.data.objects.new(name = name + "_Empty", object_data = None)
context.scene.objects.link(empty)
context.active_object.data.name = name
empty.empty_draw_type = "SPHERE"
empty.empty_draw_size = 0.00001
empty.location = obj_light['hit']
obj_light.constraints['Track To'].target = context.scene.objects.get(empty.name)
obj_light.constraints['Track To'].up_axis = "UP_Y"
obj_light.constraints['Track To'].track_axis = "TRACK_NEGATIVE_Z"
obj_light.constraints['Track To'].influence = 1
if bpy.data.objects.get("PROJECTOR_" + obj_light.data.name) is not None:
projector = bpy.data.objects["PROJECTOR_" + obj_light.data.name]
projector.constraints['Track To'].target = context.scene.objects.get(empty.name)
projector.constraints['Track To'].up_axis = "UP_Y"
projector.constraints['Track To'].track_axis = "TRACK_NEGATIVE_Z"
projector.constraints['Track To'].influence = 1
#########################################################################################################
#########################################################################################################
def remove_constraint(self, context, name):
"""Remove the empty and the constraint of the object for the orbit mode"""
obj_light = context.object
bpy.data.objects[obj_light.name].select = True
bpy.ops.object.visual_transform_apply()
empty = context.scene.objects.get(name + "_Empty")
obj_light.constraints['Track To'].influence = 0
obj_light['dir'] = (obj_light.location - Vector(obj_light['hit'])).normalized()
context.scene.objects.unlink(empty)
bpy.data.objects.remove(empty)
#########################################################################################################
#########################################################################################################
def update_constraint(self, context, event, name):
"""Update the object properties for the orbit mode"""
obj_light = context.object
empty = context.scene.objects.get(name + "_Empty")
v3d = context.space_data
rv3d = v3d.region_3d
v_m = context.area.spaces[0].region_3d.view_matrix
self.offset = -(self.initial_mouse - Vector((event.mouse_x, event.mouse_y, 0.0))) * 0.02
obj_light.location = self.initial_location + Vector(self.offset)*v_m
#---Source: http://blender.stackexchange.com/questions/21259/is-possible-to-calculate-the-shortest-distance-between-two-geometry-objects-via
lst = []
lst.append(obj_light.location)
lst.append(empty.location)
distance = math.sqrt((lst[0][0] - lst[1][0])**2 + (lst[0][1] - lst[1][1])**2 + (lst[0][2] - lst[1][2])**2)
obj_light.Lumiere.range = distance
#########################################################################################################
#########################################################################################################
def raycast_light(self, range, context, coord, ray_max=1000.0):
"""Compute the location and rotation of the light from the angle or normal of the targeted face off the object"""
scene = context.scene
i = 0
p = 0
length_squared = 0
light = context.active_object
light['pixel_select'] = False
self.reflect_angle = "View" if light.Lumiere.reflect_angle == "0" else "Normal"
#---Get the ray from the viewport and mouse
view_vector = view3d_utils.region_2d_to_vector_3d(self.region, self.rv3d, (coord))
ray_origin = view3d_utils.region_2d_to_origin_3d(self.region, self.rv3d, (coord))
ray_target = ray_origin + view_vector
#---Select the object
def visible_objects_and_duplis():
if light.Lumiere.objtarget != "":
obj = bpy.data.objects[light.Lumiere.objtarget]
yield (obj, obj.matrix_world.copy())
else :
for obj in context.visible_objects:
if obj.type == 'MESH' and "Lumiere" not in obj.data.name:
yield (obj, obj.matrix_world.copy())
#---Cast the ray
def obj_ray_cast(obj, matrix):
#---Get the ray relative to the object
matrix_inv = matrix.inverted()
ray_origin_obj = matrix_inv * ray_origin
ray_target_obj = matrix_inv * ray_target
ray_direction_obj = ray_target_obj - ray_origin_obj
#---Cast the ray
success, hit, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj)
return success, hit, normal
#---Find the closest object
best_length_squared = ray_max * ray_max
best_obj = None
#---Position of the light from the object
for obj, matrix in visible_objects_and_duplis():
i = 1
success, hit, normal = obj_ray_cast(obj, matrix)
if success :
#---Define direction based on the normal of the object or the view angle
if self.reflect_angle == "Normal" and (i == 1):
direction = (normal * matrix.inverted())
else:
direction = (view_vector).reflect(normal * matrix.inverted())
if light.Lumiere.invert_ray:
direction *= -1
#---Define range
hit_world = (matrix * hit) + (range * direction)
length_squared = ((matrix * hit) - ray_origin).length_squared
if length_squared < best_length_squared:
best_length_squared = length_squared
self.matrix = matrix
self.hit = hit
self.hit_world = hit_world
self.direction = direction
self.target_name = obj.name
#---Parent the light to the target object
light.parent = obj
light.matrix_parent_inverse = obj.matrix_world.inverted()
#---Define location, rotation and scale
if length_squared > 0 :
rotaxis = (self.direction.to_track_quat('Z','Y')).to_euler()
light['hit'] = (self.matrix * self.hit)
light['dir'] = self.direction
#---Rotation
light.rotation_euler = rotaxis
#---Lock the rotation on Horizontal or Vertical axis
if light.Lumiere.lock_light == "Vertical":
light.rotation_euler[0] = math.radians(90)
elif light.Lumiere.lock_light == "Horizontal":
light.rotation_euler[0] = math.radians(0)
if range < 0:
print("RANGE NEGATIF")
if light.Lumiere.typlight == "Env":
if light.Lumiere.rotation_lock_img:
light.Lumiere.img_rotation = light.Lumiere.img_pix_rot + math.degrees(light.rotation_euler.z)
else:
light.Lumiere.hdri_rotation = light.Lumiere.hdri_pix_rot + math.degrees(light.rotation_euler.z)
#---Location
light.location = Vector((self.hit_world[0], self.hit_world[1], self.hit_world[2]))
#---Update the position of the sun from the background texture
if light.Lumiere.typlight in ("Sky") :
update_sky(self, context)
#########################################################################################################
#########################################################################################################
def repeat_group_mat(mat, name_group):
"""Group node to repeat pattern"""
#---Group Node
pattern_group = bpy.data.node_groups.get(name_group)
if pattern_group is None:
pattern_group = bpy.data.node_groups.new(type="ShaderNodeTree", name=name_group)
#---Group inputs and outputs
pattern_group.inputs.new("NodeSocketColor","Image")
pattern_group.inputs.new("NodeSocketFloat", "Repeat X")
pattern_group.inputs.new("NodeSocketFloat", "Repeat Y")
pattern_group.outputs.new("NodeSocketColor","Image")
pattern_group.inputs[1].min_value = 0
pattern_group.inputs[2].min_value = 0
input_node = pattern_group.nodes.new("NodeGroupInput")
input_node.location = (-500, 0)
output_node = pattern_group.nodes.new("NodeGroupOutput")
output_node.location = (500, 0)
#---Add nodes to group
group_separate = pattern_group.nodes.new('ShaderNodeSeparateRGB')
group_separate.location = (-300.0, 80.0)
pattern_group.links.new(input_node.outputs['Image'], group_separate.inputs[0])
group_multiply1 = pattern_group.nodes.new('ShaderNodeMath')
group_multiply1.operation = "MULTIPLY"
group_multiply1.location = (-100.0, 80.0)
group_multiply1.inputs[1].default_value = 1
pattern_group.links.new(group_separate.outputs[0], group_multiply1.inputs[0])
pattern_group.links.new(input_node.outputs["Repeat X"], group_multiply1.inputs[1])
group_modulo1 = pattern_group.nodes.new('ShaderNodeMath')
group_modulo1.location = (100.0, 80.0)
group_modulo1.operation = "MODULO"
group_modulo1.inputs[1].default_value = 1
pattern_group.links.new(group_multiply1.outputs[0], group_modulo1.inputs[0])
group_multiply2 = pattern_group.nodes.new('ShaderNodeMath')
group_multiply2.operation = "MULTIPLY"
group_multiply2.location = (-100.0, -80.0)
group_multiply2.inputs[1].default_value = 1
pattern_group.links.new(group_separate.outputs[1], group_multiply2.inputs[0])
pattern_group.links.new(input_node.outputs["Repeat Y"], group_multiply2.inputs[1])
group_modulo2 = pattern_group.nodes.new('ShaderNodeMath')
group_modulo2.operation = "MODULO"
group_modulo2.location = (100.0, -80.0)
group_modulo2.inputs[1].default_value = 1
pattern_group.links.new(group_multiply2.outputs[0], group_modulo2.inputs[0])
group_combine = pattern_group.nodes.new('ShaderNodeCombineRGB')
group_combine.location = (300.0, 20.0)
pattern_group.links.new(group_modulo1.outputs[0], group_combine.inputs[0])
pattern_group.links.new(group_modulo2.outputs[0], group_combine.inputs[1])
pattern_group.links.new(group_combine.outputs[0], output_node.inputs[0])
group_node = mat.node_tree.nodes.new("ShaderNodeGroup")
group_node.name = name_group
group_node.node_tree = pattern_group
return(group_node)
#########################################################################################################
#########################################################################################################
def projector_mat():
"""Cycles material nodes for the front projector"""
bpy.context.scene.render.engine = 'CYCLES'
#------------------------------
#BLACK MATERIAL 1 : BASE PROJECTOR
#------------------------------
#---Create black material if not exist.
mat = bpy.data.materials.get("BASE_PROJECTOR_mat")
if mat is not None:
mat.node_tree.nodes.clear()
else:
mat = bpy.data.materials.new("BASE_PROJECTOR_mat")
mat.use_nodes= True
mat.node_tree.nodes.clear()
#---Geometry
geometry = mat.node_tree.nodes.new(type = 'ShaderNodeNewGeometry')
geometry.location = (-60.0, 520.0)
#---Diffuse Node 1
diffuse1 = mat.node_tree.nodes.new(type = 'ShaderNodeBsdfDiffuse')
diffuse1.inputs[0].default_value = [0,0,0,1]
diffuse1.location = (-60.0, 300.0)
#---Diffuse Node 2
diffuse2 = mat.node_tree.nodes.new(type = 'ShaderNodeBsdfDiffuse')
diffuse2.inputs[0].default_value = [1,1,1,1]
diffuse2.location = (-60.0, 180.0)
#---Transparent Node
trans = mat.node_tree.nodes.new(type="ShaderNodeBsdfTransparent")
trans.inputs[0].default_value = [1,1,1,1]
trans.location = (-60.0, 60.0)
#---Mix Shader Node 1
mix = mat.node_tree.nodes.new(type="ShaderNodeMixShader")
mix.location = (120.0, 300.0)
#Link Geometry Backfacing
mat.node_tree.links.new(geometry.outputs[6], mix.inputs[0])
#Link Diffuse 1
mat.node_tree.links.new(diffuse1.outputs[0], mix.inputs[1])
#Link Diffuse 2
mat.node_tree.links.new(diffuse2.outputs[0], mix.inputs[2])
#---Output Shader Node
output = mat.node_tree.nodes.new(type = 'ShaderNodeOutputMaterial')
output.location = (280.0, 300.0)
mat.node_tree.links.new(diffuse1.outputs[0], output.inputs['Surface'])
#----------------------------------
#TRANSPARENT MATERIAL 2 : PROJECTOR
#----------------------------------
#---Create a new material for cycles Engine.
cobj = bpy.context.scene.objects.active
mat_name, mat = get_mat_name(cobj.data.name)
if mat is not None:
mat.node_tree.nodes.clear()
else:
mat = bpy.data.materials.new(mat_name)
mat.use_nodes= True
# Clear default nodes
mat.node_tree.nodes.clear()
mat.alpha = 0.5
#----------------
#TEXTURE MATERIAL
#----------------
#---Repeat image group node
image_group_node = repeat_group_mat(mat, "Repeat_Texture")
image_group_node.inputs[1].default_value = 1
image_group_node.inputs[2].default_value = 1
#---Texture Coordinate
coord = mat.node_tree.nodes.new(type = 'ShaderNodeTexCoord')
coord.location = (-1040.0, -80.0)
#---Geometry
geometry = mat.node_tree.nodes.new(type = 'ShaderNodeNewGeometry')
geometry.location = (-1040.0, -340.0)
#---Repeat group for texture image
image_group_node.location = (-560.0, -20.0)
mat.node_tree.links.new(coord.outputs[0], image_group_node.inputs[0])
#---Image Texture Shader Node
texture = mat.node_tree.nodes.new(type = 'ShaderNodeTexImage')
mat.node_tree.links.new(image_group_node.outputs[0], texture.inputs[0])
texture.projection = 'BOX'
texture.location = (-380.0, 80.0)
#---Saturation
saturation = mat.node_tree.nodes.new(type = 'ShaderNodeMixRGB')
saturation.inputs['Fac'].default_value = 0
saturation.inputs['Color1'].default_value = [1,1,1,1]
saturation.inputs['Color2'].default_value = [1,1,1,1]
mat.node_tree.links.new(texture.outputs[0], saturation.inputs[1])
saturation.blend_type = 'SATURATION'
saturation.location = (-200.0, 40.0)
#---Gamma
gamma = mat.node_tree.nodes.new(type = 'ShaderNodeGamma')
mat.node_tree.links.new(saturation.outputs[0], gamma.inputs[0])
gamma.location = (-20.0, 0.0)
#---Bright / Contrast
bright = mat.node_tree.nodes.new(type = 'ShaderNodeBrightContrast')
mat.node_tree.links.new(gamma.outputs[0], bright.inputs[0])
bright.location = (160.0, 20.0)
#---Invert Node
invert = mat.node_tree.nodes.new(type="ShaderNodeInvert")
invert.inputs['Fac'].default_value = 0
mat.node_tree.links.new(bright.outputs[0], invert.inputs[1])
invert.location = (340.0, 0.0)
#-----------------
#GRADIENT MATERIAL
#-----------------
#---Mapping Node
textmap = mat.node_tree.nodes.new(type="ShaderNodeMapping")
mat.node_tree.links.new(coord.outputs[0], textmap.inputs[0])
textmap.vector_type = "TEXTURE"
textmap.location = (-820.0, -220.0)
#---Grandient Node 1
grad1 = mat.node_tree.nodes.new(type="ShaderNodeTexGradient")
mat.node_tree.links.new(textmap.outputs[0], grad1.inputs[0])
grad1.location = (-460.0, -220.0)
#---Repeat gradient group node
gradient_group_node = repeat_group_mat(mat, "Repeat_Gradient")
gradient_group_node.location = (-280.0, -220.0)
mat.node_tree.links.new(grad1.outputs[0], gradient_group_node.inputs[0])
gradient_group_node.inputs[1].default_value = 1
gradient_group_node.inputs[2].default_value = 1
#---Grandient Node 2
grad2 = mat.node_tree.nodes.new(type="ShaderNodeTexGradient")
mat.node_tree.links.new(gradient_group_node.outputs[0], grad2.inputs[0])
grad2.location = (-100.0, -220.0)
#---Color ramp
colramp = mat.node_tree.nodes.new(type="ShaderNodeValToRGB")
mat.node_tree.links.new(grad2.outputs[0], colramp.inputs[0])
colramp.location = (80.0, -120.0)
#-------
#OUTPUT
#-------
#---Geometry Node 2
geometry2 = mat.node_tree.nodes.new(type="ShaderNodeNewGeometry")
geometry2.location = (520.0, 200.0)
#---Transparent Node
trans = mat.node_tree.nodes.new(type="ShaderNodeBsdfTransparent")
trans.location = (520.0, -20.0)
#---Transparent Node 2
trans2 = mat.node_tree.nodes.new(type="ShaderNodeBsdfTransparent")
#mat.node_tree.links.new(invert.outputs[0], trans2.inputs[0])
trans2.location = (520.0, -100.0)
#---Mix Shader Node
mix = mat.node_tree.nodes.new(type="ShaderNodeMixShader")
mix.location = (700.0, 20.0)
#Link BackFacing
mat.node_tree.links.new(geometry2.outputs[6], mix.inputs[0])
#Link Transparent
mat.node_tree.links.new(trans.outputs[0], mix.inputs[1])
#Link Transparent 2
mat.node_tree.links.new(trans2.outputs[0], mix.inputs[2])
#---Light Path
light_path = mat.node_tree.nodes.new(type="ShaderNodeLightPath")
light_path.location = (700.0, 300.0)
#---ADD Math
add = mat.node_tree.nodes.new(type = 'ShaderNodeMath')
mat.node_tree.links.new(light_path.outputs[0], add.inputs[0])
mat.node_tree.links.new(light_path.outputs[3], add.inputs[1])
add.operation = 'ADD'
add.location = (880.0, 300.0)
#--------------
#EDGE THICKNESS
#--------------
#---Geometry
geometry = mat.node_tree.nodes.new(type = 'ShaderNodeNewGeometry')
geometry.location = (340.0, -200.0)
#---Grandient Node
grad3 = mat.node_tree.nodes.new(type="ShaderNodeTexGradient")
mat.node_tree.links.new(geometry.outputs[5], grad3.inputs[0])
grad3.gradient_type = 'QUADRATIC'
grad3.location = (520.0, -200.0)
#---Color ramp
edge_colramp = mat.node_tree.nodes.new(type="ShaderNodeValToRGB")
edge_colramp.color_ramp.elements[1].position = 0.025
mat.node_tree.links.new(grad3.outputs[0], edge_colramp.inputs[0])
edge_colramp.location = (700.0, -120.0)
#---Translucent Node
trans = mat.node_tree.nodes.new(type="ShaderNodeBsdfTranslucent")
mat.node_tree.links.new(edge_colramp.outputs[0], trans.inputs[0])
trans.location = (1000.0, -120.0)
#---Edge Mix Shader Node
edge_mix = mat.node_tree.nodes.new(type="ShaderNodeMixShader")
edge_mix.location = (1200.0, 20.0)
#Light path
edge_mix.inputs[0].default_value = 1
mat.node_tree.links.new(add.outputs[0], edge_mix.inputs[0])
#Link Transparent
mat.node_tree.links.new(mix.outputs[0], edge_mix.inputs[1])
#Link Translucent
mat.node_tree.links.new(trans.outputs[0], edge_mix.inputs[2])
#-------
#OUTPUT
#-------
#---Output Shader Node
output = mat.node_tree.nodes.new(type = 'ShaderNodeOutputMaterial')
output.location = (1420.0, 20.0)
mat.node_tree.links.new(edge_mix.outputs[0], output.inputs['Surface'])
#########################################################################################################
#########################################################################################################